Home > Article > Web Front-end > Detailed introduction to JavaScript execution order_Basic knowledge
Previously we explored the working principle of JavaScript from the parsing mechanism of the JavaScript engine. Below we use a more vivid example to illustrate the execution order of JavaScript code in the page. If the working mechanism of the JavaScript engine is relatively profound because it belongs to the underlying behavior, then the execution order of the JavaScript code is more vivid, because we can intuitively feel this execution order. Of course, the execution order of the JavaScript code is relatively complex, so It is also necessary to profile the JavaScript language before diving into it.
1.1 Execute JavaScript code in the order of HTML document flow
First of all, readers should know that the parsing process of HTML documents in the browser is like this: the browser follows the document flow from top to bottom Below is a step-by-step analysis of the page structure and information. JavaScript code as an embedded script should also be counted as a component of the HTML document, so the execution order of the JavaScript code during loading is also determined based on the order in which the script tag <script> appears. For example, browse the documentation page below and you will see that the code is parsed step by step from top to bottom. </p>
<p></p>
<div class="codetitle">
<span><a style="CURSOR: pointer" data="48269" class="copybut" id="copybut48269" onclick="doCopy('code48269')"><u>Copy code</u></a></span> The code is as follows:</div>
<div class="codebody" id="code48269">
<br><script><br>alert("Top script ");<br></script>
If an external JavaScript file script is imported through the src attribute of the script tag <script>, then it will also be executed in the order in which its statements appear, and the execution process is part of the document loading. Execution will not be delayed because it is an external JavaScript file. For example, move the scripts in the head and body areas of the document above to external JavaScript files, and then import them through the src attribute. Continuing to preview the page document, you will see the same order of execution. <br></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="39983" class="copybut" id="copybut39983" onclick="doCopy('code39983')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code39983"> <br><script> <p>alert("Top script");</p> <p></script>
<script></p> <p>alert("Bottom script");</p> <p></script>
1.2 The relationship between precompilation and execution order
In Javascript, function is the first type of Javascript. When we write a function, we are actually just creating an entity of type function.
Just like we can write it in the form:
The code is as follows:
alert(a); >var a =1;
alert(a); // Return value 1
Since variable declarations are processed during precompilation, they are visible to all code during execution. However, you will also see that when executing the above code, the value prompted is undefined, not 1. This is because the variable initialization process occurs during execution, not pre-compilation. During execution, the JavaScript interpreter parses the code in order. If a variable is not assigned a value in the previous line of code, the JavaScript interpreter will use the default value of undefined. Since the variable a is assigned a value in the second line, the third line of code will prompt that the value of variable a is 1, not undefined.
Similarly, in the following example, it is legal to call the function before the function is declared and can be parsed correctly, so the return value is 1.
function f(){
alert(1);
}
However, if the function is defined as follows, the JavaScript interpreter will prompt a syntax error.
var f = function(){
alert(1);
}
This is because the function defined in the above example is only assigned to the variable f as a value, so during the pre-compilation period, the JavaScript interpreter can only process the declaration of variable f, and the value of variable f can only wait until execution If you perform assignments in sequence, a syntax error will naturally occur, prompting that the object f cannot be found.
See you some examples:
Although variable and function declarations can be anywhere in the document, it is a good practice to declare global variables and functions before all JavaScript code, and to initialize and assign variables. Within a function, variables are declared first and then referenced.
1.3 Execute JavaScript code in blocks
The so-called code block is a code segment separated by <script> tags. For example, the two <script> tags below represent two blocks of JavaScript code. </p> <p></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="83113" class="copybut" id="copybut83113" onclick="doCopy('code83113')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code83113"> <br><script> <p>// JavaScript code block 1</p> <p>var a =1;</p> <p></script>
<script></p> <p>// JavaScript code block 2</p> <p>function f(){</p> <p> alert(1);</p> <p>}</p> <p></script>
When the JavaScript interpreter executes a script, it executes it in blocks. In layman's terms, if the browser encounters a <script> tag when parsing the HTML document stream, the JavaScript interpreter will wait until the code block is loaded, pre-compile the code block, and then execute it. After execution, the browser continues to parse the HTML document stream below, and the JavaScript interpreter is ready to process the next block of code. </p> <p>Since JavaScript is executed in blocks, if you call a variable or function declared in a subsequent block in a JavaScript block, a syntax error will be prompted. For example, when the JavaScript interpreter executes the following code, it will prompt a syntax error, showing that variable a is undefined and object f cannot be found. </p> <p></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="35451" class="copybut" id="copybut35451" onclick="doCopy('code35451')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code35451"> <br><script> <p>// JavaScript code block 1</p> <p>alert(a);</p> <p>f();</p> <p></script>
<script></p>
<p>// JavaScript code block 2</p>
<p>var a =1;</p>
<p>function f(){</p>
<p> alert(1);</p>
<p>}</p>
<p></script>
Although JavaScript is executed in blocks, different blocks belong to the same global scope, which means that variables and functions between blocks can be shared.
1.4 Use the event mechanism to change the order of JavaScript execution
Since JavaScript processes code in blocks and follows the parsing order of the HTML document flow, you will see such syntax errors in the above example. But when the document stream is loaded, such an error will not occur if it is accessed again. For example, if the code that accesses the variables and functions in the second block of code is placed in the page initialization event function, there will be no syntax errors.
<script></p>
<p>// JavaScript code block 2</p>
<p>var a =1;</p>
<p>function f(){</p>
<p> alert(1);</p>
<p>}</p>
<p></script>
For security reasons, we generally only allow JavaScript code execution after the page is initialized. This can avoid the impact of network speed on JavaScript execution, and also avoid the restrictions on JavaScript execution caused by HTML document flow.
Attention
If there are multiple windows.onload event handlers in a page, only the last one is valid. In order to solve this problem, you can put all scripts or calling functions in the same onload event handler. For example:
f1();
f2();
f3();
}
And in this way, the execution order of functions can be changed by simply adjusting the order of calling functions in the onload event handler.
In addition to page initialization events, we can also change the execution order of JavaScript code through various interactive events, such as mouse events, keyboard events, clock triggers, etc. For detailed explanation, please refer to Chapter 14.
1.5 Execution order of JavaScript output scripts
In JavaScript development, the write() method of the document object is often used to output JavaScript scripts. So how are these dynamic output scripts executed? For example:
Please note that the JavaScript script string output using the document.write() method must be placed in the <script> tag that is also output, otherwise the JavaScript interpreter will not recognize these legal JavaScript codes and treat them as ordinary The string is displayed in the page document. For example, the following code will display the JavaScript code instead of executing it. </p> <p></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="94458" class="copybut" id="copybut94458" onclick="doCopy('code94458')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code94458"> <br>document.write('f();'); <p>document.write('function f(){');</p> <p>document.write('alert(1);');</p> <p>document.write(');');<br></p> </div> <p>However, there are certain risks in outputting and executing scripts through the document.write() method, because different JavaScript engines execute them in different orders, and different browsers may also have bugs in parsing. </p> <p>Ø Problem 1: The variables or functions declared in the external JavaScript file imported through the document.write() method cannot be found. For example, look at the sample code below. </p> <p></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="27974" class="copybut" id="copybut27974" onclick="doCopy('code27974')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code27974"> <br>document.write('<script type="text /javascript" src="http://www.jb51.net/test.js"> <p></script>');
document.write('');
Alert (n 1); // All browsers will prompt that the variable can not find the variable n
The code of the external JavaScript file (test.js) is as follows:
Ø Question 2: Different JavaScript engines have slightly different execution orders for output external import scripts. For example, look at the sample code below.
document.write('');
alert(n 3);
alert(n);
The execution sequence in IE browser is shown in Figure 1-6.
Figure 1-6 IE 7 browser execution sequence and prompted syntax errors
The execution order in browsers that comply with DOM standards is different from that in IE browsers, and there are no syntax errors. Figure 1-7 shows the execution order in Firefox 3.0 browser.
Figure 1-7 Firefox 3 browser execution sequence and prompted syntax errors
Resolve the different execution orders in different browsers and possible bugs. We can put all external files imported using the output script in independent code blocks, so that this problem can be avoided according to the execution order of the JavaScript code blocks introduced above. For example, for the above example, you can design it like this:
document.write('');
alert(n 3); // Tip 4
alert(n 4); // Tip 5
In this way, the above code can be executed in order in different browsers, and the output order is 1, 2, 3, 4 and 5. The reason for the problem is: a contradiction between the output imported script and the current JavaScript code block. If output separately, there will be no conflict.