JavaScript Execution Order Detail _ Basics

Source: Internet
Author: User
Tags script tag

To explore how JavaScript works from the JavaScript engine's parsing mechanism, let's use a more vivid example to illustrate the order in which JavaScript code is executed on the page. If the JavaScript engine works more profoundly because it belongs to the underlying behavior, then the sequence of JavaScript code execution is more vivid because we can intuitively feel the execution order, and of course the sequence of JavaScript code execution is rather complicated, So it is necessary to dissect the JavaScript language before delving into it.
1.1 Executing JavaScript code in HTML document flow order
First, the reader should be aware that the parsing process for HTML documents in the browser is as follows: The browser progressively parses the page structure and information from top to bottom according to the document flow. JavaScript code as an embedded script should also be part of an HTML document, so the order in which JavaScript code is loaded is also determined by the order in which the script label <script> appears. For example, if you browse the following document page, you will see that the code is parsed from top to bottom.

Copy Code code 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 execute in the order in which the statements appear, and the execution process is part of the document load. Will not be deferred because it is an external JavaScript file. For example, move the header and main area script in the above document to 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 Code code 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, a function is the first type of JavaScript. When we write down a function, we simply create an entity with a function type.
Just as we can write in this form:

Copy Code code as follows:

Functionhello ()
{
Alert ("Hello");
}
Hello ();
Varhello = function ()
{
Alert ("Hello");
}
Hello ();

are actually the same. But when we make changes to the functions in them, we find the strange problem.
Copy Code code as follows:

<scripttype= "Text/javascript" >
Functionhello () {
Alert ("Hello");
}
Hello ();
Functionhello () {
Alert ("Hello World");
}
Hello ();
</script>

We'll see the result: two consecutive times Hello world.
Rather than the Hello and hello world we imagined.
This is because JavaScript does not fully interpret the execution in sequence, but rather to "precompile" the JavaScript before it is interpreted, and in the process of precompilation, the defined function is executed first, and all VAR variables are created with the default value of undefined. To improve the efficiency of program execution.
That is to say, a piece of code is actually precompiled by JS engine to this form:
Copy Code code as follows:

<scripttype= "Text/javascript" >
Varhello = function () {
Alert ("Hello");
}
Hello = function () {
Alert ("Hello World");
}
Hello ();
Hello ();
</script>

We can see clearly from the above code that the function is also a data and a variable, and we can assign a value to the function (re-assign).
Of course, in order to prevent such a situation, we can also do this:
Copy Code code 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 the script, it processes all declared variables and functions during the precompiled period.

Do the following:

1. A similar "precompiled" operation is performed before execution: first, the active object in 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 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 of the execution phase, when a variable needs to be resolved, it is first looked up from the active object in 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 is looked up by the scope chain Encountered var a = ... Such statements will be assigned to the corresponding variable (note: The assignment of the variable is done in the interpretation of the execution phase, if the variable is used before, its value will be undefined) so, there will be no error when the JavaScript interpreter executes the following script:

Copy Code code 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 for all code during execution. However, you will also see that the value of the hint is undefined, rather than 1, by executing the code above. This is because the variable initialization process occurs during the execution period, not the precompiled period. During the execution period, the JavaScript interpreter is parsed in code order, and the JavaScript interpreter uses the default value undefined if no value is assigned to the variable in the preceding line of code. Because you assign a value to variable a in the second row, the third line of code prompts the value of variable A to be 1 instead of undefined.

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

Copy Code code as follows:

f (); Call function, return value 1

function f () {

Alert (1);

}

However, if you define a function in the following manner, the JavaScript interpreter prompts for a syntax error.

Copy Code code as follows:

f (); Call function, return syntax error

var f = function () {

Alert (1);

}

This is because the function defined in the preceding example is assigned only as a value to the variable F, so in the precompiled period, the JavaScript interpreter can only handle declaring the variable F, but for the value of the variable F, you can only wait until the execution period in order to assign the value, there will be a syntax error, the hint can not find the object F.

Goodbye some examples:

Copy Code code as follows:

<script type= "Text/javascript" >

/* During precompilation func is an attribute of 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!")

}

/* A VAR was encountered during execution to "this is a variable" * *

Alert (func); This is a variable

</script>

Copy Code code as follows:

<script type= "Text/javascript" >
var name = "Feng"; function func ()
{
/* First, in the Func environment, first assign the name to the undefined, and then in the execution process to look for the active object in the Func environment of the Name property, the previous precompiled 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 variable and function declarations can be anywhere in the document, it is good practice to declare global variables and functions before all JavaScript code and initialize the variables. Inside the function, you declare the variable first and then reference it.

1.3 Execute JavaScript code by block

A code block is a code snippet separated by a <script> label. For example, the following two <script> tags represent two JavaScript code blocks respectively.

Copy Code code as follows:

<script>

JavaScript code block 1

var a = 1;

</script>

<script>

JavaScript code block 2

function f () {

Alert (1);

}

</script>

When the JavaScript interpreter executes the script, it executes by block. In layman's parlance, when a browser parses an HTML document stream, if it encounters a <script> tag, the JavaScript interpreter waits until the code block is loaded, precompiling the code block before executing. 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 later block is invoked in a JavaScript block. For example, when the JavaScript interpreter executes the following code, it prompts for a syntax error, showing that variable A is undefined and object F is not found.

Copy Code code 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 chunks and follows the parsing order of the HTML document stream, this syntax error is seen in the example above. However, when the document flow is loaded, this error will not occur if you access it again. For example, the code that accesses variables and functions in the 2nd block of code is placed in the page initialization event function, and there is no syntax error.

Copy Code code 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 execution after the page is initialized, which avoids the effect of speed on JavaScript execution, and also avoids the HTML document flow restrictions on JavaScript execution.

Attention

If you have multiple Windows.onload event handlers on one page, only the last one is valid, and to solve this problem, you can put all scripts or call functions in the same onload event handler, for example:

Copy Code code as follows:

Window.onload = function () {

F1 ();

F2 ();

F3 ();

}

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

In addition to page initialization events, we can change the sequence of JavaScript code execution through various interaction events, such as mouse events, keyboard events, and clock triggers, for details, see Chapter 14th.

1.5 The order in which JavaScript output scripts are executed

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

Copy Code code as follows:

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

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

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

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

document.write ('} ');

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


Run the above code, we will find: the document.write () method to write the output of the script string to the location of the script, the browser after parsing document.write () the contents of the document, continue to parse document.write () output , and then parse the following HTML documents in order. In other words, the code string that the JavaScript script outputs is executed immediately after the output.

Note that JavaScript script strings that are output using the document.write () method must be placed in <script> tags that are also exported, otherwise the JavaScript interpreter will not be able to recognize these legitimate JavaScript codes. As an ordinary string, it is displayed in the page document. For example, the following code will show the JavaScript code instead of executing it.

Copy Code code as follows:

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

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

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

document.write (');

However, there is a risk of exporting scripts and executing through the document.write () method, because different JavaScript engines have different order of execution, and bugs occur when different browsers parse.

Ø one, the variables or functions declared in an external JavaScript file imported through the document.write () method cannot be found. For example, look at the sample code below.

Copy Code code 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 hint cannot find the variable n

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

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

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

Copy Code code as follows:

var n = 1;

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

Question two, different JavaScript engines have a slightly different order of execution for external import scripts for output. For example, look at the sample code below.

Copy Code code 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 Code code as follows:

var n = 1;

alert (n);

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

Figure 1-6 IE 7 Browser execution order and hint syntax error

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

Figure 1-7 Firefox 3 Browser execution order and hint syntax error

Resolves different order of execution for different browsers and possible bugs. We can avoid this problem by placing the external files that are imported using output scripts in separate blocks of code so that the sequence of JavaScript code blocks described above can be avoided. For example, for the example above, you can design this:

Copy Code code 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 that the output of the imported script is inconsistent with the current JavaScript code block. If you output alone, there is no conflict.

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.