Javascript-based asynchronous loading of js file functions (supporting passing parameters through arrays) _ javascript skills

Source: Internet
Author: User
Tags getscript
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;
}
})();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.