jQuery getScript() vs document.createElement('

2020-06-03 05:35发布

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);
}

3条回答
Deceive 欺骗
2楼-- · 2020-06-03 05:52

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.

查看更多
\"骚年 ilove
3楼-- · 2020-06-03 05:53

the documentation to Jquery method says:

Load a JavaScript file from the server using a GET HTTP request, then execute it.

That means the imported javascript will be straigt invoked after successful loading.

Appending to the head: It means the browser adds the script-tag as a last child and executes the content (it is the same if you add the tag manuelly at the end of the head tag). Appending to the body: It means the browser adds the script-tag as a last child of the body tag and executes that content (it is the same if you add the tag manuelly at the end of the body tag).

查看更多
Emotional °昔
4楼-- · 2020-06-03 06:04

It is worth mentioning that jQuery's getScript function disables caching by default, meaning that browsers will download the script every time the page is requested (see previous answer here). Your loadScript function, on the other hand, should take advantage of caching.

查看更多
登录 后发表回答