Home  >  Article  >  Web Front-end  >  Asynchronous loading js file function written in javascript (supports array parameter passing)_javascript skills

Asynchronous loading js file function written in javascript (supports array parameter passing)_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:45:281250browse

Load js files for your own use, supports multiple files, not compatible with IE

Copy code The code is as follows:

/**
* Load js file
* @param {string || array} url js path
* @param {Function} fn Callback after loading is completed
* @return {object} game object
* @example
* getScript("url.js",fn)
* getScript(["url-1.js","url-2.js"],fn)
*/
game .getScript = (function() {
var cache = {};//Cache the url internally, and will not request it next time
return function(url, fn) {
if ("string" == = typeof(url)) {
url = [url]; //If it is not an array, bring a set
};
var i = 0,//Loop
ok = 0,// Several js loaded successfully
len = url.length,//How many js in total
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 loaded
(ok >= len && fn) && fn();//If all js are loaded, execute the callback
continue;
}
cache[encodeURIComponent(_url) ] = !0;//Set cache
js = create(_url);//Create js
fn && (js.onload = function() {
if ( ok >= len) {/ /If all js are loaded, execute the callback
fn();
}
});
};
head = js = _url = create = null;
return this ;
}
})();
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn