JS dynamically loads scripts and performs callback operations. js dynamic script callback

Source: Internet
Author: User

JS dynamically loads scripts and performs callback operations. js dynamic script callback

Many people may have encountered the problem of loading other js files in javascript, but many may not know how to determine whether the js files to be loaded are loaded, if the loading is not completed, the function in the file will not be called successfully. This article explains how to load other js files in js and execute the callback function after loading.

We can dynamically create the <script> element and then modify its src attribute to load the script. But how can we know that the script file has been loaded, because some of our functions can be executed only after the Script Loading takes effect.
After searching for resources on the network, I found that the onreadystatechange element of the <script> element can be used in the IE browser to monitor changes in the loading status, and determine whether the script is loaded by judging whether its readyState is loaded or complete. Instead, the IE browser can use onload to directly determine whether the script is loaded.

A simple implementation process looks like this:

// In IE: var script = document. createElement ("script"); script. setAttribute ("type", "text/javascript"); script. onreadystatechange = function () {if (this. readyState = "loaded" | this. readyState = "complete") {alert ("loading successful! ") ;}} Script. setAttribute ("src", scripts [I]); // Opera, FF, Chrome, etc.: var script = document. createElement ("script"); script. setAttribute ("type", "text/javascript"); script. onload = function () {alert ("loading successful! ");} Script. setAttribute (" src ", scripts [I]);

The principle is very simple. Based on these two simple principles, we made some modifications. I changed them to two functions: serial loading and parallel loading scripts.

When an array containing multiple JS file paths is uploaded, the serial loading function starts from loading the first script file. Each successful loading starts to load the next script file, after loading all the data, run the callback function. Parallel loading is to load all the script files at the beginning, that is, they load from the same point. When all the files are loaded, the callback function is executed.

The two functions are tested to be compatible with all mainstream browsers.

/*** Concatenate the specified script * concatenate and load [asynchronous] one by one, after each load is complete, load the next * All loaded and then execute the callback * @ param array | string specified scripts * @ param function after the success of the callback function * @ return array all generated scripts array of element objects */function seriesLoadScripts (scripts, callback) {if (typeof (scripts )! = "Object") var scripts = [scripts]; var HEAD = document. getElementsByTagName ("head "). item (0) | document.doc umentElement; var s = new Array (), last = scripts. length-1, recursiveLoad = function (I) {// recursive 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 [synchronize] concurrently, whether or not the last one is loaded, directly load all * after loading is complete, execute callback * @ param array | string specified scripts * @ param function after successful callback function * @ return array all generated script element object arrays */function parallelLoadScripts (scripts, callback) {if (typeof (scripts )! = "Object") var scripts = [scripts]; var HEAD = document. getElementsByTagName ("head "). item (0) | document.doc umentElement, 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 <script> label is dynamically inserted into the You will also find that a method called Conditional compilation is used 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 online for learning.

The usage of these two functions: here we declare an array variable, which contains two remote JS file addresses (of course, the <script> tag call script supports cross-origin ):

Var scripts = ["http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js", "http://wellstyled.com/files/jquery.debug/jquery.debug.js"]; // The two files are jQuery 1. 4. library file and jQuery Debug plug-in // then you can use the following method to call and execute the callback after the success. SeriesLoadScripts (scripts, function () {/* debug = new $. debug ({posTo: {x: 'right', y: 'bottom '}, width: '480px', height: '000000', itemDivider: '

The Series-loaded function is used here. Of course, you can also use the parallel loading function. This function can be used as needed. We recommend that you use the series-loaded function for each script that depends on the previous script, otherwise, the parallel connection is faster than the serial connection.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.