title: How to inject <script> tag into empty iframe without document.write?
body: <p>I want to load an <code>iframe</code> 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 <code>&lt;script&gt;</code> tag to load the JavaScript file, but that would require two requests to the server.</p>
  
  <p>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.</p>
  
  <p>Something like this works on all browsers:</p>
  
  <pre><code>function createScriptFrame(container, url) {
      const frame = document.createElement('iframe');
      container.appendChild(frame);
      const doc = frame.contentDocument;
      doc.open();
      doc.write('&lt;html&gt;&lt;body&gt;&lt;script src="' + url + '"&gt;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;');
      doc.close();
  }
  </code></pre>
  
  <p>But using <code>document.write</code> is a really nasty way of doing it. Chrome even complains with a warning in the console: <em>[Violation] Avoid using document.write().</em></p>
  
  <p>I've come up with a few alternative approaches, for example:</p>
  
  <pre><code>// same as above until doc.open()
  const s = doc.createElement('script');
  s.src = url;
  doc.head.appendChild(s);
  </code></pre>
  
  <p>or</p>
  
  <pre><code>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);
  </code></pre>
  
  <p>These work nicely in Chrome and Safari but <strong>not in Firefox</strong>.</p>
  
  <p>I've compiled a test with several methods to load the script: <a href="https://embed.plnkr.co/l8DwUBQs7cQsi938eTOn/" rel="nofollow noreferrer">https://embed.plnkr.co/l8DwUBQs7cQsi938eTOn/</a></p>
  
  <p>Any ideas how to make this work?</p>