The JS callback function is used to execute the corresponding callback function after the js script is loaded.
This problem often occurs in projects: When a js script is loaded and then executed, many friends may not know how to determine whether the js file to be loaded is loaded, if the loading is not completed, it is impossible to call the functions in the js file. This article mainly explains how to execute the corresponding callback task after successfully loading the js file.
Basic Ideas
We can dynamically create<script>
Element, and then load the script by changing its src attribute. But how do you know that the script file has been loaded? Some functions can be called only after the script is loaded. Available in IE browser<script>
Elementonreadystatechange
To monitor the changes in the loading status, and determine whether the script is loaded by determining whether its readyState is loaded or complete. Instead, the IE browser can use onload to directly determine whether the script is loaded.
Simple Dynamic script example
A simple implementation process is as follows:
// In IE: var HEAD = document. getElementsByTagName ('head') [0] | document.doc umentElementvar src = 'HTTP: // xxxxxx.com 'var script = document. createElement ('script') script. setAttribute ('type', 'text/javascript ') script. onreadystatechange = function () {if (this. readyState = 'loaded' | this. readyState = 'complete') {console. log ('Load successful! ')} Script. setAttribute ('src', src) HEAD. modern browsers such as appendChild (script) // Chrome: var HEAD = document. getElementsByTagName ('head') [0] | document.doc umentElement; var src = 'HTTP: // xxxxxx.com 'var script = document. createElement ('script') script. setAttribute ('type', 'text/javascript ') script. onload = function () {console. log ('Load successful! ')} Script. setAttribute ('src', src) HEAD. appendChild (script)
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.
Serial and parallel dynamic 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.
/*** Load the specified script serially * load [asynchronous] one by one, after each load is complete, load the next * after loading all, execute the callback * @ param {Array | String} scripts to specify the script to be loaded * @ param {Function} callback Function * @ return {Array} All generated script element object arrays */function seriesLoadScripts (scripts, callback) {if (typeof (scripts )! = 'Object') {var scripts = [scripts];} var HEAD = document. getElementsByTagName ('head') [0] | document.doc umentElement; var s = []; var last = scripts. length-1; // recursive var recursiveLoad = function (I) {s [I] = document. createElement ('script'); s [I]. setAttribute ('type', 'text/javascript '); // Attach handlers for all browsers // asynchronous s [I]. onload = s [I]. onreadystatechange = function () {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 ()};}} // synchronize 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, run the callback * @ param {Array | String} scripts to specify the script to be loaded * @ param {Function} callback Function after success * @ return {array} All generated script element object arrays */function parallelLoadScripts (scripts, Callback) {if (typeof (scripts )! = 'Object') {var scripts = [scripts];} var HEAD = document. getElementsByTagName ('head') [0] | document.doc umentElement; var s = []; var loaded = 0; for (var I = 0; I <scripts. length; I ++) {s [I] = document. createElement ('script'); s [I]. setAttribute ('type', 'text/javascript '); // Attach handlers for all browsers // asynchronous s [I]. onload = s [I]. onreadystatechange = function () {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 () ;}}; // synchronize s [I]. setAttribute ('src', scripts [I]); HEAD. appendChild (s [I]);}
Here<script>
Dynamically insert tags to the pageThe tag is automatically removed after being loaded.
Usage
An array variable is declared here, which contains two remote JS file addresses (of course<script>
The 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. ParallelLoadScripts (scripts, function () {/* debug = new $. debug ({posTo: {x: 'right', y: 'bottom '}, width: '480px', height: '000000', itemDivider: '
Summary
The above section describes how to execute the corresponding callback function after loading JS scripts. I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!