I read Ruan Yifeng’s article Detailed explanation of jQuery’s deferred object some time ago, and gained some understanding of
the usage of deferred in jQuery. Today I saw an article in the garden:
About refactoring The failure experience of JS front-end framework (by the way, I miss those dead codes), so I shared a solution I wrote before that uses jQuery's deferred to asynchronously load JS files in order. Corrections are welcome.
If you don’t understand deferred in jQuery yet, I strongly recommend you to read Ruan Yifeng’s detailed explanation of jQuery’s deferred object.
The code to load the JS file is as follows:
/*
Loading JavaScript Asynchronously
loadScript.load(["a.js", "b.js"]);
*/
var loadScript = (function() {
var loadOne = function (url) {
var dtd = $.Deferred();
var node = document.createElement('script');
node.type = "text/javascript";
var onload = function(){
dtd.resolve();
};
$(node).load(onload).bind('readystatechange', function(){
if (node.readyState == 'loaded'){
onload();
}
});
document.getElementsByTagName('head')[0].appendChild(node);
node.src = url;
return dtd.promise();
};
var load = function(urls) {
if(!$.isArray(urls)) {
return load([ urls]);
}
var ret = [];
for (var i = 0; i < urls.length; i ) {
ret[i] = loadOne(urls[i ]);
};
return $.when.apply($, ret);
}
return {
load: load
};
})() ;
The code is relatively simple and will not be explained here. Here is a calling example.
For example, there are two JS files in the project: a.js and b.js. The code is as follows:
a.js:
var a = "i am in a.js";
var b = "i am in a.js";
b.js:
var a = " i am in b.js";
var b = "i am in b.js";
If we want to load b.js first and then a.js, example The code is as follows:
Loading JavaScript Asynchronously
The results are as follows:
Here we can see that the variables defined in b.js are overwritten by those in a.js.
Go to the Elements panel, we can see that b.js and a.js are added to the head in sequence:
For such problems, everyone is welcome to share your own solutions.