Best way to dynamically load a script

I need to load some js files dynamically and sequentially (i.e. the second script load after loading the full first, third after second, etc.).

Question: how was it discovered when the script was loaded? I ran into problems with the onload event - it does not fire in IE8. After reading this , I tried subscribing to onreadystatechange and wrote very ugly code to load the script:

function loadScript(url, callback) { var isLoaded = false; var script = document.createElement('script'); script.onreadystatechange = function () { if ((script.readyState == 'complete' || script.readyState == 'loaded') && !isLoaded) { if (callback) callback(); } }; script.setAttribute('type', 'text/javascript'); script.setAttribute('src', url); document.head.appendChild(script); }; 

Can you offer the best cross browser solution without such tricks?

UPD: Thanks for the answers. What if I need to download jquery.js (for example, the client has an old version) :)?

+6
source share
4 answers

I think you need jQuery.getScript

The function accepts the URL and the success method, with which you can link the loading of scripts and, therefore, load them sequentially:

 jQuery.getScript( url, function() { jQuery.getScript( url2, function() {/*... all 2 scripts finished loading */} ); }); 
+10
source

Here is my snippet for loading multiple scripts using jQuery.getScript ();

 function getScripts(inserts, callback) { var nextInsert = inserts.shift(); if (nextInsert != undefined) { console.log("calling"+nextInsert); jQuery.getScript(nextInsert, function(){ getScripts(inserts, callback); }) .fail(function(jqxhr, settings, exception){alert("including "+nextInsert+" failed:\n" +exception)}); } else { if (callback != undefined) callback(); } }; 

Using:

 var includes = [ "js/script1.js", "js/script2.js", "js/script3.js" ]; getScripts(includes, function(){ /* typically a call to your init method comes here */; }); 
+8
source

RequireJS :

... is the loader of the JavaScript file and module. It is optimized for use in a browser, but it can be used in other JavaScript environments such as Rhino and Node. Using a modular script loader, such as RequireJS, will improve the speed and quality of your code.

Says it's IE 6+, Firefox2 2+, Safari 3.2+, Chrome 3+, and Opera 10+.

+2
source

In Chrome, we can use onload and onerror to replace onreadystatechange .

-1
source

Source: https://habr.com/ru/post/895346/


All Articles