This article mainly introduces javascript-written asynchronous loading of js file functions. It also supports a single file and multiple files (array passing parameters), but is not compatible with IE6, for more information about how to load js files, see <G id = "1"> add multiple files </G>.
The Code is as follows:
/**
* Load js files
* @ Param {string | array} url js path
* @ Param {Function} callback after fn is loaded
* @ Return {object} game object
* @ Example
* GetScript ("url. js? 6.1.3 ", fn)
* GetScript (["url-1.js? 6.1.3 "," url-2.js? 6.1.3 "], fn)
*/
Game. getScript = (function (){
Var cache ={}; // The url in the internal cache, which is not requested next time
Return function (url, fn ){
If ("string" === typeof (url )){
Url = [url]; // if it is not an array with a set
};
Var I = 0, // starts from the loop
OK = 0, // Successful loading of several js
Len = url. length, // a total of several js
Head = document. getElementsByTagName ("head") [0],
Js, _ url,
Create = function (url) {// create js
Js = document. createElement ("script ");
Js. type = "text/javascript ";
Js. src = url;
Head. appendChild (js );
Return js;
};
For (; I <len ;){
If (cache [encodeURIComponent (_ url = url [I ++]) {// if
(++ OK> = len & fn) & fn (); // if all js files are loaded, the callback is executed.
Continue;
}
Cache [encodeURIComponent (_ url)] =! 0; // set Cache
Js = create (_ url); // create a js
Fn & (js. onload = function (){
If (++ OK> = len) {// if all js files are loaded, the callback is executed.
Fn ();
}
});
};
Head = js = _ url = create = null;
Return this;
}
})();