Many people may have encountered the problem of loading other js files in JavaScript, but many friends may not know how to judge whether the js file we want to load has been loaded. If we do not complete the load, we will not succeed. This article explains how to load other js files in js and execute callback functions after loading.
We can create a <script> element dynamically and then load the script by changing its src attribute, but how do we know that the script file has been loaded? Because some of our functions need to be executed after the script is loaded and taken effect.
After searching for resources on the network, I found that in the IE browser, you can use the onreadystatechange of the <script> element to monitor the change in the loading state, and determine whether the script is loaded or completed by judging whether its readyState is loaded or completed. Instead of IE browsers, you can use onload to directly determine whether the script is loaded.
A simple implementation process looks like this:
//IE under: var script = document.createElement("script");script.setAttribute("type","text/javascript");script.onreadystatechange = function() { if(this.readyState == "loaded" || this.readyState == "complete"){ alert("Loaded successfully!"); }}script.setAttribute("src",scripts[i]);//Opera, FF, Chrome, etc.: var script = document.createElement("script");script.setAttribute("type","text/javascript");script.onload = function() { alert("Loaded successfully!");}script.setAttribute("src",scripts[i]);The principle is very simple. Based on these two simple principles, we made some modifications, and I changed it to two functions, namely serial loading and parallel loading scripts.
When passing an array containing multiple JS file paths, the serial loading function starts from the first script file loading. Each time one is loaded successfully, the next script file will be loaded. After all the loading is completed, the callback function will be executed. Parallel loading is to load all script files from the beginning, that is, they start from the same point, and when all loading is completed, the callback function is executed.
After testing, these two functions are compatible with all current mainstream browsers.
/** * Concatenate loading of the specified script* Concatenate loading [asynchronous] loading one by one, each loading is completed, the next one is loaded * After all loading is completed, the callback is executed* @param array|string The specified scripts* @param function The function called back after success* @return array All generated script element object 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) { //Recursives 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);} /** * Load the specified script in parallel * Load in parallel [Synchronous] at the same time, regardless of whether the previous load is completed or not, load all directly* Execute the callback after all loading is completed* @param array|string The specified scripts* @param function Callback function after success* @return array All generated script element object 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.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 <script> tag is dynamically inserted into the <head> tag in the page, and the tag element will be automatically removed after loading.
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 not an IE browser. Conditional compilation is not the focus of this article. If you are interested, you can search for relevant materials for learning.
How to use these two functions: Here we declare an array variable that contains two remote JS file addresses (of course, the <script> tag call 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"];//These two files are the library files of jQuery 1.4. and the jQuery Debug plugin// Then you can use the following method to call and execute the callback after success. seriesLoadScripts(scripts,function(){ /* debug = new $.debug({ posTo : { x:'right', y:'bottom' }, width: '480px', height: '50%', itemDivider : '<hr>', listDOM : 'all' }); */ alert('Script loading is complete');});The function loaded in series is used here. Of course, you can also use parallel loading functions. This can be used according to the situation. It is recommended that each next script has dependence on the previous script to use serial loading, otherwise use parallel connection, because in principle, parallel connection is faster than serial connection.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.