The JS callback function is used to execute the corresponding callback function after the js script is loaded.

Source: Internet
Author: User

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> ElementonreadystatechangeTo 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!

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.