简体   繁体   中英

Adding external scripts in DOM from javascript code

I have included 3 external js files at the end of body. Suppose my document already contains a js named as insertlibs.js and here is the code

var script1 = document.createElement('script');
script1.src='http://code.jquery.com/jquery-latest.js';
script1.type='text/javascript';
document.getElementsByTagName('Body').item(0).appendChild(script1);

// Similar way to include underscore

var script2 = document.createElement('script');
script2.src='hhttp://documentcloud.github.com/backbone/backbone-min.js';
script2.type='text/javascript';
document.getElementsByTagName('Body').item(0).appendChild(script2);  

But what is happening sometimes, it is throwing an error that $ is not defined and I tried to debug in Firefox and there is a parallel download occurring for jquery and backbone and sometimes backbone library getting download earlier than jQuery which is causing this error.

As far as i know that if a script tag is included, it will block further request So as soon as I add jquery in dom. I am confused about the workflow here happening.

So i have found the solution, I merged both the js and making a single call which is working perfectly but that does not explain me the flow happening in above case. Please help.

This is because you are attempting to include backbone without ensuring that jquery has been completely loaded. To correct this, you can use the script's onload attribute to attach a callback which will be fired when jquery is loaded.

For ex:

var script1 = document.createElement('script');
script1.src='http://code.jquery.com/jquery-latest.js';
script1.type='text/javascript';

// add an onload handler
script1.onload = function() {

   // load the rest of the scripts here

   var script2 = document.createElement('script');
   script2.src='hhttp://documentcloud.github.com/backbone/backbone-min.js';
   script2.type='text/javascript';
   document.getElementsByTagName('Body').item(0).appendChild(script2);
}

document.getElementsByTagName('Body').item(0).appendChild(script1);

As far as i know that if a script tag is included, it will block further request

No, the blocking / synchronous download is only when the tags are right in the parsed HTML (or are inserted via document.write during the parse); dynamically DOM-appended scripts load asynchronously and in parallel.

To do that but ensure that scripts are executed when their dependencies are met, you need to use AMD loaders.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM