Javascript write asynchronous load js file function of support array pass arguments

  • 2020-03-30 03:17:06
  • OfStack



game.getScript = (function() {
 var cache = {};//The url is cached internally and not requested next time
 return function(url, fn) {
  if ("string" === typeof(url)) {
   url = [url]; //If it's not an array with a sleeve
  };
  var i = 0,//Cycle up
   ok = 0,//Load several js successfully
   len = url.length,//How many js
   head = document.getElementsByTagName("head")[0],
   js, _url,
   create = function(url) {//Create a 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 it's loaded
    (++ok >= len && fn) && fn();//If all js is loaded, a callback is executed
    continue;
   }
   cache[encodeURIComponent(_url)] = !0;//Set the cache
   js = create(_url);//Create a js
   fn && (js.onload = function() {
    if (++ok >= len) {//If all js is loaded, a callback is executed
     fn();
    }
   });
  };
  head = js = _url = create  = null;
  return this;
 }
})();


Related articles: