If you do not know about deferred in jQuery, the following section describes how to asynchronously load JS files from the deferred object, if you are interested, you can refer to the following explanation of jQuery's deferred object by referring to some time ago. I have some knowledge about the deferred usage in jQuery. Today I see an article in the garden: experiences in JS front-end framework refactoring (by the way, those dead code will be missed), so I will share one of my previous JS file loading schemes asynchronously using jQuery's deferred, thank you for your correction.
If you do not know about deferred in jQuery, it is strongly recommended that you take a look at the deferred object details of jQuery.
The code for loading a JS file is as follows:
The Code is as follows:
/*
Loading JavaScript Asynchronously
LoadScript. load (["a. js? 6.1.3 "," B. js? 6.1.3 "]);
*/
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 ('readystatechang', 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 I will not explain it here. The following is a call example.
For example, the project contains two JS files: a. js and B. js. The Code is as follows:
A. js:
The Code is as follows:
Var a = "I am in a. js? 6.1.3 ";
Var B = "I am in a. js? 6.1.3 ";
B. js:
The Code is as follows:
Var a = "I am in B. js? 6.1.3 ";
Var B = "I am in B. js? 6.1.3 ";
If we want to load B. js first and then a. js, the sample code is as follows:
The Code is as follows:
Loading JavaScript Asynchronously