Home  >  Article  >  Web Front-end  >  Detailed explanation of how to use javascript to load a script and execute callback code examples

Detailed explanation of how to use javascript to load a script and execute callback code examples

伊谢尔伦
伊谢尔伦Original
2017-07-21 15:38:311200browse

We can dynamically create the 3f1c4e4b6b16bbbd69b2ee476dc4f83a element, and then load the script by changing its src attribute, but how do we know that the script file is loaded, because some of our functions need to take effect after the script is loaded? to start execution. In IE browser, you can use onreadystatechange of 3f1c4e4b6b16bbbd69b2ee476dc4f83a element to monitor the change of loading state, and determine whether the script is loaded by judging whether its readyState is loaded or complete. Non-IE browsers can use onload to directly determine whether the script is loaded.

A simple implementation process looks like this:


//IE下:
var script = document.createElement("script");
script.setAttribute("type","text/javascript");
script.onreadystatechange = function() {
  if(this.readyState == "loaded" || this.readyState == "complete"){
    alert("加载成功啦!");
  }
}
script.setAttribute("src",scripts[i]);

//Opera、FF、Chrome等:
var script = document.createElement("script");
script.setAttribute("type","text/javascript");
script.onload = function() {
  alert("加载成功啦!");
}
script.setAttribute("src",scripts[i]);

The principle is very simple. Based on these two simple principles, we Make some modifications, namely serial loading and parallel loading scripts.

When an array containing multiple JS file paths is passed, the serial loading function starts from loading the first script file. Each time one is successfully loaded, it starts loading the next script file. All loads are completed. Then execute the callback function. Parallel loading loads all script files from the beginning, that is, they start loading from the same point. When all loading is completed, the callback function is executed.

After testing, these two functions are compatible with all current mainstream browsers.


##

/** 
 * 串联加载指定的脚本
 * 串联加载[异步]逐个加载,每个加载完成后加载下一个
 * 全部加载完成后执行回调
 * @param array|string 指定的脚本们
 * @param function 成功后回调的函数
 * @return array 所有生成的脚本元素对象数组
 */
function seriesLoadScripts(scripts,callback) {
  if(typeof(scripts) != "object") var scripts = [scripts];
  var HEAD = document.getElementsByTagName("head").item(0) || document.documentElement;
  var s = new Array(), last = scripts.length - 1, recursiveLoad = function(i) { //递归
    s[i] = document.createElement("script");
    s[i].setAttribute("type","text/javascript");
    s[i].onload = s[i].onreadystatechange = function() { //Attach handlers for all browsers
      if(!/*@cc_on!@*/0 || this.readyState == "loaded" || this.readyState == "complete") {
        this.onload = this.onreadystatechange = null; this.parentNode.removeChild(this); 
        if(i != last) recursiveLoad(i + 1); else if(typeof(callback) == "function") callback();
      }
    }
    s[i].setAttribute("src",scripts[i]);
    HEAD.appendChild(s[i]);
  };
  recursiveLoad(0);
}
 

/**
 * 并联加载指定的脚本
 * 并联加载[同步]同时加载,不管上个是否加载完成,直接加载全部
 * 全部加载完成后执行回调
 * @param array|string 指定的脚本们
 * @param function 成功后回调的函数
 * @return array 所有生成的脚本元素对象数组
 */

function parallelLoadScripts(scripts,callback) {
  if(typeof(scripts) != "object") var scripts = [scripts];
  var HEAD = document.getElementsByTagName("head").item(0) || document.documentElement, s = new Array(), loaded = 0;
  for(var i=0; i<scripts.length; i++) {
    s[i] = document.createElement("script");
    s[i].setAttribute("type","text/javascript");
    s[i].onload = s[i].onreadystatechange = function() { //Attach handlers for all browsers
      if(!/*@cc_on!@*/0 || this.readyState == "loaded" || this.readyState == "complete") {
        loaded++;
        this.onload = this.onreadystatechange = null; this.parentNode.removeChild(this); 
        if(loaded == scripts.length && typeof(callback) == "function") callback();
      }
    };
    s[i].setAttribute("src",scripts[i]);
    HEAD.appendChild(s[i]);
  }
}

Here, the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag is dynamically inserted into the 93f0f5c25f18dab9d176bd4f6de5d30e tag of the page, and the tag element will be automatically removed after the loading is completed. .

If you are careful, you will also find that a method called conditional compilation is used here as an expression (!/*@cc_on!@*/0) to determine whether it is a non-IE browser. This article is not about conditional compilation. If you are interested, you can search for relevant information online to learn.

How to use these two functions: Here we declare an array variable, which contains two remote JS file addresses (of course the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag calling script supports cross-domain) :


var scripts = [ 
  "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js",
  "http://wellstyled.com/files/jquery.debug/jquery.debug.js"
];

//这两个文件分别是 jQuery 1.4.的库文件和 jQuery Debug 插件
//然后你可以使用下面的方法调用并在成功后执行回调了。

seriesLoadScripts(scripts,function(){ 

  /*
  debug = new $.debug({ 
    posTo : { x:&#39;right&#39;, y:&#39;bottom&#39; },
    width: &#39;480px&#39;,
    height: &#39;50%&#39;,
    itempider : &#39;<hr>&#39;,
    listDOM : &#39;all&#39;
  }); 

  */
  alert(&#39;脚本加载完成啦&#39;);
});

What is used here is the serial loading function. Of course, you can also use the parallel loading function. This can be used according to the situation. It is recommended that each next script be matched with the previous script. Use series loading if there are dependencies, otherwise use parallel connection, because in principle parallel connection is faster than series connection.


The above is the detailed content of Detailed explanation of how to use javascript to load a script and execute callback code examples. For more information, please follow other related articles on the PHP Chinese website!

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