Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied! <p>Seriously, why didn't this show up when I searched? <a href="https://stackoverflow.com/questions/7557868/document-head-document-body-to-attach-scripts">document.head, document.body to attach scripts</a></p> <p>Comment links to a perfect explanation: <a href="http://www.jspatterns.com/the-ridiculous-case-of-adding-a-script-element/" rel="nofollow noreferrer">The ridiculous case of adding a script element</a>.</p> <p>Essentially, you have several options:</p> <ul> <li><h3>hook to head</h3> <pre class="lang-js prettyprint-override"><code>document.getElementsByTagName('head')[0].appendChild(js) </code></pre> <ol> <li><strong>Pro</strong> - most pages have a head</li> <li><strong>Con</strong> - not always autogenerated if not; traversal</li> </ol></li> <li><h3>hook to body</h3> <pre class="lang-js prettyprint-override"><code>document.body.appendChild(js); </code></pre> <ol> <li><strong>Pro</strong> - shortest, no traversal</li> <li><strong>Con</strong> - "operation aborted" error in IE7 if not executed from direct child of <code>body</code></li> </ol></li> <li><h3>hook to <code>documentElement</code></h3> <pre class="lang-js prettyprint-override"><code>var html = document.documentElement; html.insertBefore(js, html.firstChild); </code></pre> <ol> <li><strong>Pro</strong> - always exists, minimal traversal</li> <li><strong>Con</strong> - <a href="http://www.stevesouders.com/blog/2010/05/11/appendchild-vs-insertbefore/#comment-2084" rel="nofollow noreferrer">or does it?</a> (fails if first child is a comment)</li> </ol></li> <li><h3>hook to first script</h3> <pre class="lang-js prettyprint-override"><code>var first = document.getElementsByTagName('script')[0]; first.parentNode.insertBefore(js, first); </code></pre> <ol> <li><strong>Pro</strong> - most likely always calling your dynamic load from a script</li> <li><strong>Con</strong> - will fail if no previous scripts exist; traversal</li> </ol></li> </ul> <p>So, the conclusion is -- you can do it any way, but you have to think of your audience. If you have control of where your loader is being executed, you can use <code>document.body</code>. If your loader is part of a library that other people use, you'll have to give specific instructions depending on what method you used, and be prepared for people abusing your specs.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload