Home > Web Front-end > JS Tutorial > 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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 16:45:28
Original
1295 people have browsed it

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 ;
}
})();
Related labels:
Statement of this Website
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
Latest Issues
What are JavaScript hook functions?
From 1970-01-01 08:00:00
0
0
0
What is JavaScript garbage collection?
From 1970-01-01 08:00:00
0
0
0
c++ calls javascript
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template