Home > Web Front-end > JS Tutorial > body text

javascript写的异步加载js文件函数(支持数组传参)_javascript技巧

WBOY
Release: 2016-05-16 16:45:28
Original
1215 people have browsed it

自己用的加载js文件,支持多文件,不兼容ie

复制代码 代码如下:

/**
 * 加载js文件
 * @param  {string || array}   url   js路径
 * @param  {Function} fn      加载完成后回调
 * @return {object}           game对象
 * @example
 * getScript("url.js",fn)
 * getScript(["url-1.js","url-2.js"],fn)
 */
game.getScript = (function() {
 var cache = {};//内部缓存下url,下次则不请求
 return function(url, fn) {
  if ("string" === typeof(url)) {
   url = [url]; //如果不是数组带个套
  };
  var i = 0,//循环起
   ok = 0,//加载成功几个js
   len = url.length,//一共几个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    if (cache[encodeURIComponent((_url = url[i++]))]) {//如果加载过
    (++ok >= len && fn) && fn();//如果加载完所有的js则执行回调
    continue;
   }
   cache[encodeURIComponent(_url)] = !0;//设置缓存
   js = create(_url);//创建js
   fn && (js.onload = function() {
    if (++ok >= len) {//如果加载完所有的js则执行回调
     fn();
    }
   });
  };
  head = js = _url = create  = null;
  return this;
 }
})();
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!