I want to load an iframe that does nothing else than load a JavaScript file from a given URL. While this would be easy by loading a simple HTML page into the iframe that only contains the <script> tag to load the JavaScript file, but that would require two requests to the server.
So my idea is to write the code to load the JS file from the calling method in the parent window into the empty iframe.
Something like this works on all browsers:
function createScriptFrame(container, url) {
const frame = document.createElement('iframe');
container.appendChild(frame);
const doc = frame.contentDocument;
doc.open();
doc.write('<html><body><script src="' + url + '"></script></body></html>');
doc.close();
}
But using document.write is a really nasty way of doing it. Chrome even complains with a warning in the console: [Violation] Avoid using document.write().
I've come up with a few alternative approaches, for example:
// same as above until doc.open()
const s = doc.createElement('script');
s.src = url;
doc.head.appendChild(s);
or
const s = doc.createElement('script');
s.appendChild(doc.createTextNode('(function() { const s =
document.createElement("script"); s.src = "' + url + '";
document.body.appendChild(s); })()'));
doc.head.appendChild(s);
These work nicely in Chrome and Safari but not in Firefox.
I've compiled a test with several methods to load the script: https://embed.plnkr.co/l8DwUBQs7cQsi938eTOn/
Any ideas how to make this work?