Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
}
like image 990
bebeastie Avatar asked Apr 26 '11 13:04

bebeastie


1 Answers

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.

like image 115
pawel Avatar answered Oct 15 '22 04:10

pawel