


Detailed explanation of how to use javascript to load a script and execute callback code examples
We can dynamically create the <script> 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. </script>In IE browser, you can use onreadystatechange of <script> 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. </script>
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 <script> tag is dynamically inserted into the <head> tag of the page, and the tag element will be automatically removed after the loading is completed. . <p> 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. <br/><br/>How to use these two functions: Here we declare an array variable, which contains two remote JS file addresses (of course the <script> tag calling script supports cross-domain) : <p><p class="jb51code"><br/><pre class='brush:php;toolbar:false;'>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;); });</pre> 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. <p><br/></script>
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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment