Some time ago, I read a detailed article on jQuery's deferred object and learned some about the usage of deferred in jQuery. Today I saw 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:
Copy codeThe Code 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 ('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:
Copy codeThe Code is as follows:
Var a = "I am in a. js ";
Var B = "I am in a. js ";
B. js:
Copy codeThe Code is as follows:
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, the sample code is as follows:
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Meta charset = "UTF-8">
<Title> Loading JavaScript Asynchronously </title>
<Script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type = "text/javascript"> </script>
<Script src = "jls. js" type = "text/javascript"> </script>
</Head>
<Body>
<Script type = "text/javascript">
LoadScript. load (["B. js", "a. js"]). done (function (){
Test ();
});
Function test (){
Console. log ("var a =" + a + ", var B =" + B );
}
</Script>
</Body>
</Html>
The result is as follows:
Here we can see that the variables defined in B. js are overwritten by a. js.
Go to the Elements panel and we can see that B. js and a. js are added to the head sequentially:
You are welcome to share your solutions for such issues.