jQuery getScript() vs document.createElement('script')

bebeastie picture bebeastie · Apr 26, 2011 · Viewed 11.2k times · Source

Assuming that both of these approaches load the script properly, and that I wait the appropriate amount of time before using the script (and/or use a callback), what are the major differences between these approaches.

Note: I understand the first uses jQuery (which is a larger download etc.). What I'm really interested in is the after affects of these approaches. Does one place the script in a different scope than the other? Etc.

jQuery:

function loadScript() {
    $.getScript('http://www.mydomain/myscript.js');
}

Appending to body:

function loadScript() {
   var script= document.createElement('script');
   script.type= 'text/javascript';
   script.src= 'http://www.mydomain/myscript.js';
   script.async = true;
   document.body.appendChild(script);
}

Appending to head:

function loadScript() {
   var head= document.getElementsByTagName('head')[0];
   var script= document.createElement('script');
   script.type= 'text/javascript';
   script.src= 'http://www.mydomain/myscript.js';
   script.async = true;
   head.appendChild(script);
}

Answer

pawel picture pawel · Apr 26, 2011

jQuery appends the script element to head if present, or to document element otherwise. Under the hood the code is similar. The final result will be the same: both approaches execute new code in the global scope.