Detailed JavaScript execution sequence

Source: Internet
Author: User
Tags script tag

This article mainly describes the JavaScript execution sequence, the need for friends can refer to

Before exploring the workings of JavaScript from the JavaScript engine's parsing mechanism, let's look at a more graphic example of how JavaScript code executes in a page. If the JavaScript engine works more esoteric because it is the underlying behavior, then the JavaScript code execution order is more image, because we can intuitively feel this execution order, of course, JavaScript code Execution order is more complex, So it is necessary to dissect the JavaScript language before you dive into it.
1.1 Executing JavaScript code in HTML document flow order
First, readers should be aware that HTML documents are parsed in the browser: The browser is parsing the page structure and information from top to bottom in a document flow. JavaScript code should also be part of an HTML document as an embedded script, so the order in which JavaScript code is loaded is determined by the order in which the script tags <script> appear. For example, browse the following document page and you will see that the code is parsed from top to bottom.

Copy CodeThe code is as follows:
<script>
Alert ("Top script");
</script>
<script>
Alert ("head script");
</script>
<title></title>
<body>
<script>
Alert ("page script");
</script>
</body><script>
Alert ("Bottom script");
</script>

If you import an external JavaScript file script through the script tag <script> src attribute, it will also be executed in the order in which the statements appear, and the execution is part of the document loading. Do not postpone execution because it is an external JavaScript file. For example, move the script in the header and body area of the above document into an external JavaScript file and import it through the SRC attribute. Continue previewing the page document and you will see the same order of execution.

Copy CodeThe code is as follows:
<script>

Alert ("Top script");

</script>

<script src= "Http://www.jb51.net/head.js" ></script>

<title></title>

<body>

<script src= "Http://www.jb51.net/body.js" ></script>

</body>

<script>

Alert ("Bottom script");

</script>

1.2 The relationship between precompilation and execution order

In JavaScript, function is the first type of JavaScript. When we write down a function, it is actually a type of entity that is created.
Just as we can write in this form:

Copy CodeThe code is as follows:
Functionhello ()
{
Alert ("Hello");
}
Hello ();
Varhello = function ()
{
Alert ("Hello");
}
Hello ();


In fact, they are all the same. But when we make changes to the functions, we find a strange problem.

Copy CodeThe code is as follows:
<scripttype= "Text/javascript" >
Functionhello () {
Alert ("Hello");
}
Hello ();
Functionhello () {
Alert ("Hello World");
}
Hello ();
</script>


We'll see the result: two consecutive Hello world.
Rather than our imagined Hello and Hello world.
This is because JavaScript is not fully interpreted in sequence, but rather as a "precompiled" javascript before it is interpreted, and in the pre-compilation process, the defined function takes precedence, and all var variables are created with the default value of undefined. To improve the execution efficiency of the program.
In other words, the above code is actually precompiled by the JS engine into this form:

Copy CodeThe code is as follows:
<scripttype= "Text/javascript" >
Varhello = function () {
Alert ("Hello");
}
Hello = function () {
Alert ("Hello World");
}
Hello ();
Hello ();
</script>


We can clearly see from the code above that the function is also the data and the variable, and we can assign (re-assign) the "function".
Of course, in order to prevent such a situation, we can also:

Copy CodeThe code is as follows:
<scripttype= "Text/javascript" >
Functionhello () {
Alert ("Hello");
}
Hello ();
</script>
<scripttype= "Text/javascript" >
Functionhello () {
Alert ("Hello World");
}
Hello ();
</script>


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

When the JavaScript engine parses a script, it processes all declared variables and functions during the precompiled period.

Do the following:

1. A "precompiled" operation is performed before execution: first, a live object under the current execution environment is created, and those variables declared with VAR are set to the properties of the active object, but at this point the assignment of these variables is undefined. The functions defined by the function are also added as properties of the active object, and their values are the function definitions.

2. In interpreting the execution phase, when a variable needs to be parsed, it is first looked up from the active object of the current execution environment, and if it is not found and the owner of the execution environment has the prototype attribute, it is looked up from the prototype chain, otherwise it will be found by the scope chain. Encountered var a = ... Such a statement will assign a value to the corresponding variable (note: The assignment of the variable is done during the interpretation execution phase, and if the variable is used before this, its value will be undefined) Therefore, it will appear that the JavaScript interpreter executes the following script without error:

Copy CodeThe code is as follows:
alert (a); return value undefined

var a = 1;

alert (a); return value 1


Because variable declarations are processed during the precompiled period, they are visible to all code during execution. However, you will also see that executing the above code, the value of the hint is undefined, not 1. This is because the variable initialization process occurs at the execution time, not the precompilation period. During the execution period, the JavaScript interpreter is parsed in code order, and the JavaScript interpreter uses the default value, undefined, if the variable is not assigned a value in the preceding line of code. Because the variable a is assigned in the second row, the value of variable A is indicated in the third line of code as 1, not undefined.

Similarly, the following example calls a function before the function declaration is legitimate and can be parsed correctly, so the return value is 1.

Copy CodeThe code is as follows:
f (); Call function, return value 1

function f () {

Alert (1);

}

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

Copy CodeThe code is as follows:
f (); Call function, return syntax error

var f = function () {

Alert (1);

}

This is because the function defined in the example above is assigned only as a value to the variable F, so during the precompiled period, the JavaScript interpreter can only handle declaring the variable F, whereas for the value of the variable F, only wait for the execution period to be assigned in order, there is a natural syntax error that indicates that object F cannot be found.

Goodbye some examples:

Copy CodeThe code is as follows:
<script type= "Text/javascript" >

/* During the precompilation process, Func is a property in the active object in the window environment, and the value is a function that overrides the undefined value */

Alert (func); function func () {alert ("hello!")}

var func = "This is a variable"

function func () {

Alert ("hello!")

}

/* encountered Var re-assigned as "This is a variable" during execution */

Alert (func); This is a variable

</script>

Copy CodeThe code is as follows:
<script type= "Text/javascript" >
var name = "Feng"; function func ()
{
/* First, the name is assigned to undefined in the Func environment, and then during execution, the Name property of the active object in the func environment is first searched, and the pre-compiled value is undefined, so the output is undefined, not feng*/
alert (name); Undefined var name = "JSF";
alert (name); Jsf
}
Func ();
alert (name);
Feng
</script>

Although variables and function declarations can be anywhere in the document, a good habit should be to declare global variables and functions before all JavaScript code, and to initialize variables to be assigned values. Inside a function, the variable is declared before it is referenced.

1.3 Executing JavaScript code by block

The so-called code block is the code snippet separated by the <script> tag. For example, the following two <script> tags represent two javascript blocks of code, respectively.

Copy CodeThe code is as follows:
<script>

JavaScript code block 1

var a = 1;

</script>

<script>

JavaScript code block 2

function f () {

Alert (1);

}

</script>

The JavaScript interpreter executes the script as a block. In layman's words, when the browser parses an HTML document stream, if it encounters a <script> tag, the JavaScript interpreter waits until the block is loaded, pre-compiles the block of code, and then executes it. After execution, the browser continues to parse the following HTML document stream, and the JavaScript interpreter is ready to process the next block of code.

Because JavaScript is executed in blocks, a syntax error is prompted if a variable or function declared in a subsequent block is called in a JavaScript block. For example, when the JavaScript interpreter executes the following code, it prompts a syntax error, shows that the variable A is undefined, and object F cannot be found.

Copy CodeThe code is as follows:
<script>

JavaScript code block 1

alert (a);

f ();

</script>

<script>

JavaScript code block 2

var a = 1;

function f () {

Alert (1);

}

</script>

Although JavaScript is executed by block, different blocks belong to the same global scope, meaning that variables and functions between blocks can be shared.

1.4 Changing JavaScript execution order with event mechanism

Because JavaScript handles code in blocks, and then follows the parsing order of the HTML document flow, you see this syntax error in the example above. However, when the document flow is loaded, there is no such error if it is accessed again. For example, the code that accesses the variables and functions in the 2nd block of code is placed in the page initialization event function, and there is no syntax error.

Copy CodeThe code is as follows:
<script>

JavaScript code block 1

Window.onload = function () {//page initialization event handler

alert (a);

f ();

}

</script>

<script>

JavaScript code block 2

var a = 1;

function f () {

Alert (1);

}

</script>

For security reasons, we typically allow JavaScript code to execute after the page has been initialized, which avoids the effect of speed on javascript execution, and avoids the limitations of HTML document flow for JavaScript execution.

Attention

If there is more than one Windows.onload event handler in a page, only the last one is valid, in order to solve this problem, you can put all the script or call functions in the same onload event handler, for example:

Copy CodeThe code is as follows:
Window.onload = function () {

F1 ();

F2 ();

F3 ();

}

In this way, you can change the order in which the functions are executed by simply adjusting the order in which the function is called in the OnLoad event handler.

In addition to the page initialization events, we can also change the order of JavaScript code execution through various interactive events, such as mouse events, keyboard events, and clock triggers, for more information, see Chapter 14th.

1.5 JavaScript output Script execution order

In JavaScript development, JavaScript scripts are often output using the write () method of the Document object. So how are these dynamic output scripts executed? For example:

Copy CodeThe code is as follows:
document.write (' <script type= ' text/javascript ' > ');

document.write (' f (); ');

document.write (' function f () {');

document.write (' alert (1); ');

document.write ('} ');

document.write (' </script> ');


Running the above code, we will find: the document.write () method first writes the output script string to the document location where the script is located, and the browser resumes parsing the contents of the document.write () output after parsing the contents of the document document.write () , and then parse the subsequent HTML document sequentially. That is, the code string that the JavaScript script outputs is executed immediately after the output.

Note that the JavaScript script string output using the document.write () method must be placed in a <script> tag that is also output, otherwise the JavaScript interpreter cannot recognize these legitimate JavaScript code. As a normal string, it is displayed in the page document. For example, the following code will display the JavaScript code instead of executing it.

Copy CodeThe code is as follows:
document.write (' f (); ');

document.write (' function f () {');

document.write (' alert (1); ');

document.write ('); ');

However, there is also a risk of outputting the script through the document.write () method, because different JavaScript engines have different order of execution and a bug occurs when different browsers parse.

? Problem one, a variable or function declared in an external JavaScript file imported through the document.write () method cannot be found. For example, look at the following sample code.

Copy CodeThe code is as follows:
document.write (' <script type= "Text/javascript" src= "Http://www.jb51.net/test.js" >

</script> ');

document.write (' <script type= ' text/javascript ' > ');

document.write (' alert (n); '); IE hints that the variable n cannot be found

document.write (' </script> ');

alert (n+1); All browsers will be prompted to not find the variable n

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

Copy CodeThe code is as follows:
var n = 1;


Test in different browsers, you will find prompt syntax error, can not find the variable N. That is, if you access the variables contained in an external JavaScript file in a script that is exported using the document.write () method in this code block in a JavaScript code block, a syntax error is displayed. At the same time, if in IE, not only in the script, but also in the output of the script will be prompted to find the output of the import of external JavaScript file variables (the expression is a bit long and around, do not understand the reader can try to run the above code can understand).

? In question two, different JavaScript engines perform a slightly different sequence of output external import scripts. For example, look at the following sample code.

Copy CodeThe code is as follows:
<script type= "Text/javascript" >

document.write (' <script type= "Text/javascript" src= "Http://shaozhuqing.com/test1.js" >

</script> ');

document.write (' <script type= ' text/javascript ' > ');

document.write (' alert (2); ')

document.write (' Alert (n+2); ');

document.write (' </script> ');

</script>

<script type= "Text/javascript" >

alert (n+3);

</script>


The code for the external JavaScript file (test1.js) is shown below.

Copy CodeThe code is as follows:
var n = 1;

alert (n);

The order of execution in IE is shown in 1-6.

Figure 1-6 IE 7 Browser execution sequence and syntax errors for hints

The order of execution in a DOM-compliant browser is different from IE, and there is no syntax error, and 1-7 shows the order of execution in the Firefox 3.0 browser.

Figure 1-7 Firefox 3 Browser execution sequence and hints syntax error

Resolve different execution sequences that exist for different browsers, as well as possible bugs. All external files that are imported using output scripts can be placed in separate blocks of code, which can be avoided by executing the sequence of JavaScript code blocks described above. For example, for the example above, you can design this:

Copy CodeThe code is as follows:
<script type= "Text/javascript" >

document.write (' <script type= ' text/javascript ' src= ' http://www.jb51.net/test1.js ' ></script> ');

</script>

<script type= "Text/javascript" >

document.write (' <script type= ' text/javascript ' > ');

document.write (' alert (2); '); Tip 2

document.write (' Alert (n+2); '); Tip 3

document.write (' </script> ');

alert (n+3); Tip 4

</script>

<script type= "Text/javascript" >

alert (n+4); Tip 5

</script>

This allows the above code to be executed sequentially in different browsers, and the output order is 1, 2, 3, 4, and 5. The problem is caused by the contradiction between the output of the imported script and the current JavaScript code block. There is no conflict if the output is separate.

Detailed JavaScript execution sequence

Related Article

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.