JavaScript write asynchronous Load JS file function (support array parameter) _javascript tips

Source: Internet
Author: User
Tags getscript

own use of loading JS files, supporting multiple files, incompatible IE

Copy Code code as follows:

/**
* Load JS file
* @param {string | | | | array} URL JS path
* @param {Function} fn load Complete callback
* @return {Object} game objects
* @example
* Getscript ("Url.js", FN)
* Getscript (["Url-1.js", "Url-2.js"],FN)
*/
Game.getscript = (function () {
var cache = {};//internal cache URL, next time do not request
return function (URL, fn) {
if ("string" = = typeof (URL)) {
url = [url]; If not an array with a set
};
var i = 0,//loop
OK = 0,//loaded successfully several JS
Len = url.length,//altogether several JS
Head = document.getElementsByTagName ("head") [0],
JS, _url,
create = function (URL) {//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 loaded
(++ok >= len && fn) && fn ()//If all JS is loaded, execute the callback
Continue
}
Cache[encodeuricomponent (_url)] =!0;//Set Cache
JS = Create (_url);//JS
fn && (js.onload = function () {
if (++ok >= len) {//If all JS is loaded then the callback is executed
FN ();
}
});
};
Head = JS = _url = create = null;
return this;
}
})();

Related Article

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.