In just about every example I come across for injecting a script dynamically with javascript, it ends with:
document.getElementsByTagName("head")[0].appendChild(theNewScriptTag)
Even yepnope.js attaches new scripts before the first script in the page, like:
var firstScript = doc.getElementsByTagName( "script" )[ 0 ];
firstScript.parentNode.insertBefore( theNewScriptTag, firstScript );
My question is: why not just append it to the document body?
document.body.appendChild(theNewScriptTag);
It just seems to me that the DOM-traversal involved with getElementsByTagName
-- or even the whole "insertAfter = parent.insertBefore" trick -- is wasting resources.
Is there a detriment to dynamically adding your scripts to the very bottom?
Seriously, why didn't this show up when I searched? document.head, document.body to attach scripts
Comment links to a perfect explanation: The ridiculous case of adding a script element.
Essentially, you have several options:
document.getElementsByTagName('head')[0].appendChild(js)
document.body.appendChild(js);
body
documentElement
var html = document.documentElement;
html.insertBefore(js, html.firstChild);
var first = document.getElementsByTagName('script')[0];
first.parentNode.insertBefore(js, first);
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 document.body
. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With