Home > Web Front-end > JS Tutorial > Detailed introduction to JavaScript execution order_Basic knowledge

Detailed introduction to JavaScript execution order_Basic knowledge

WBOY
Release: 2016-05-16 17:10:50
Original
1469 people have browsed it

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>

<script><br>alert("head script");<br></script>



<script><br>alert("page script");<br></ script><br></body></html><br><script><br>alert("bottom 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:

Copy the code The code is as follows:

functionHello()
{
alert("Hello");
}
Hello();
varHello = function()
{
alert("Hello") ;
}
Hello();

Actually, they are all the same. But when we modify the functions, we will find very strange problems.
Copy code The code is as follows:

 ​ 
functionHello() {                                                                                   🎜>Hello();



We will see the result like this: Hello World is output twice in a row.
Not the Hello and Hello World we imagined.
This is because Javascript is not completely interpreted and executed in sequence, but Javascript is "precompiled" before interpretation. During the precompilation process, the defined functions will be executed first, and all functions will be executed first. The var variable is created and the default value is undefined to improve the execution efficiency of the program.
That is to say, the above piece of code is actually pre-compiled by the JS engine into this form:
Copy the code The code is as follows:

                                                                            ) {
                                                                                                                                                     From the above code, we can clearly see that functions are also data and variables. We can also assign (reassign) values ​​to "functions".
Of course, in order to prevent this situation, we can also do this:




Copy the code


The code is as follows:


  
functionHello() {    
alert("Hello");    Hello();   ; functionHello() { alert("Hello World"); } Hello();


In this way, the program is divided into two sections, and the JS engine will not put them together. 

When the JavaScript engine parses the script, it will process all declared variables and functions during pre-compilation.

Do the following:

1. An operation similar to "precompilation" will be performed before execution: first, an active object in the current execution environment will be created, and those variables declared with var will be set as attributes of the active object, but at this time these variables The assignment values ​​are all undefined, and those functions defined as function are also added as properties of the active object, and their values ​​are exactly the definition of the function.

2. During the interpretation and execution phase, when a variable needs to be parsed, it will first be searched from the active object of the current execution environment. If it is not found and the owner of the execution environment has the prototype attribute, it will be searched from the prototype chain. , otherwise it will be searched according to the scope chain. When encountering a statement such as var a = ..., the corresponding variable will be assigned a value (note: the assignment of the variable is completed during the interpretation and execution phase. If the variable is used before this, its value will be undefined). Therefore, just It will appear that no error will be reported when the JavaScript interpreter executes the following script:



Copy code

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.

Copy code The code is as follows:

f();

function f(){

alert(1);

}

However, if the function is defined as follows, the JavaScript interpreter will prompt a syntax error.

Copy code The code is as follows:

f();

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:

Copy code The code is as follows:

Copy code The code is as follows:

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.

Copy code The code is as follows:

<script> <p>// JavaScript code block 1</p> <p>window.onload = function(){ // Page initialization event handler function</p> <p> alert(a);</p> <p> f();</p> <p>}</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>

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:

Copy code The code is as follows:

window.onload = function(){

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:

Copy code The code is as follows:

document.write('');


Run the above code, we will find that: the document.write() method first writes the output script string to the document location where the script is located, and the browser continues to parse after parsing the content of the document where document.write() is located. The content output by document.write() is then parsed in order to parse the following HTML documents. In other words, the code string output by the JavaScript script will be executed immediately after output.

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:

Copy the code The code is as follows:

var n = 1;

When tested in different browsers, you will find a syntax error and the variable n cannot be found. In other words, if you access the variables contained in the external JavaScript file imported in the script output using the document.write() method in this code block in a JavaScript code block, a syntax error will be displayed. At the same time, if in the IE browser, not only in the script, but also in the output script, it will be prompted that the output variable imported into the external JavaScript file cannot be found (the expression is a bit long and convoluted, readers who do not understand can try to run the above code can be understood).

Ø Question 2: Different JavaScript engines have slightly different execution orders for output external import scripts. For example, look at the sample code below.

Copy code The code is as follows:

');

document.write('');



The code for the external JavaScript file (test1.js) is as follows.
Copy code The code is as follows:

var n = 1;

alert(n);

The execution sequence in IE browser is shown in Figure 1-6.

Detailed introduction to JavaScript execution order_Basic knowledge

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.

Detailed introduction to JavaScript execution order_Basic knowledge

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:

Copy code The code is as follows:

');

');

alert(n 3); // Tip 4

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.

Related labels:
source:php.cn
Previous article:How to write classes with private attributes in JavaScript (1)_javascript skills Next article:Discuss jQuery’s ajax usage scenarios (c#)_jquery
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Latest Issues
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template