An analysis of the _javascript skill of browser executing JavaScript script loading and code execution sequence

Source: Internet
Author: User
Tags file url script tag

This article mainly based on the introduction of JavaScript to the HTML page of several ways to analyze the HTML JavaScript script execution sequence problem

1. About the blocking of JavaScript script execution

JavaScript has a blocking feature when it is parsed and executed in the browser, that is, when JavaScript code executes, the page parsing, rendering, and other resource downloads are stopped to wait for the script to finish ①. This is uncontroversial, and the behavior is consistent across all browsers, and the reason is understandable: browsers need a stable DOM structure, and JavaScript may modify the DOM (changing the DOM structure or modifying a DOM node). If you continue parsing the page while you are executing JavaScript, the entire parsing process becomes unmanageable and the parsing error may become large.

But here's one more thing to note, for external scripting, there's also the process of downloading a script, in an earlier browser, the download of JavaScript files not only blocks the parsing of the page, it even blocks the downloads of other resources on the page (including other JavaScript script files, external CSS files and external resources such as pictures. Allowing JavaScript to be downloaded in parallel from IE8, firefox3.5, Safari4, and chrome2, while downloading JavaScript files does not block downloads of other resources (in older versions, Downloading JavaScript files can also block downloads of other resources.

Note: Different browsers for the same domain name under the maximum number of connections have different restrictions, HTTP1.1 protocol specification can not be higher than 2, but most browsers currently provide more than 2 of the maximum number of connections, IE6/7 are 2, IE8 promoted to 6, Firefox and Chrome is also 6, of course, this setting can also be modified, the details can refer to: http://www.stevesouders.com/blog/2008/03/20/roundup-on-parallel-connections/

2. About the order in which scripts are executed

Browsers parse pages in order from top to bottom, so it is normal for JavaScript scripts to execute sequentially from top to bottom, that is, the first code that appears on the page, or the code that is introduced first, is always executed first, even when JavaScript files are allowed to be downloaded in parallel. Notice that we are marking the "normal situation" here, what is the reason? We know that there are several ways to add JavaScript code to HTML, as follows (regardless of the module loader such as Requirejs or SEAJS):

(1) Normal introduction: That is, in the page through the <script> tag to introduce scripting code or to introduce external scripts

(2) Write <script> tag or code to page via Document.Write method

(3) through the dynamic scripting technology, that is, using the DOM interface to create <script> elements, and set the element src, and then add the elements into the DOM.

(4) Get the script content through Ajax, then create the <script> element, set the element's text, and add the element into the DOM.

(5) The JavaScript code is written directly in the element's event handler or directly as the principal of the URL, as shown in the following example:

<!--write directly in the element's event handler-->
<input type= "button" value= "click to test" onclick= "alert (' clicked Button ')"/>
<!-- As the principal--> of the URL

The 5th scenario has little effect on the order in which we discuss the script execution, so we'll only discuss the first four cases here:

2.1 When the normal introduction of the script

When the script is introduced normally, the JavaScript code executes from top to bottom, regardless of whether the script is downloaded in parallel or executed in the order in which it was introduced, we take the following demo for example:

First, a script is written through PHP, which receives two parameters, file URL and latency time, and the script sends the contents of the file to the browser after the delay time passed in, as follows:

<?php
$url = $_get[' url '];
$delay = $_get[' delay '];
if (Isset ($delay)) {Sleep
($delay);
}
Echo file_get_contents ($url);

In addition, we have defined two JavaScript files, 1.js and 2.js respectively, in this case the code for the two is as follows:

1.js

Alert ("I am the first script");

2.js

Alert ("I am the second script");

Then we introduce the scripting code in HTML:

<script src= '/delayfile.php?url=http://localhost/js/load/1.js&delay=3 ' type= ' Text/javascript ' ></ script>
<script type= "Text/javascript" >
alert ("I am an internal script");
</script>

Although the first script is delayed by 3 seconds to return, in all browsers the order of the pop-up is the same: "I am the first script"-> "I am the internal script"-> "I am the second script"

2.2 When writing scripts to the page via document.write

document.write when the document stream is not closed, the content is written to the location immediately after the end of the script location, and the browser executes the current short code, and then parses what Document.Write writes.

Note: There is also a problem with the location of the document.write write to the contents of the

There are some issues with document.write writing scripts that need to be categorized for description:

[1] Only external scripts are written to the same <script> tag via document.write:

In this case, the execution order of the external scripts is always lower than the code in the tag that introduces the script, and executes in the order introduced, we modify the code in the HTML:

<script src= '/delayfile.php?url=http://localhost/js/load/1.js&delay=2 ' type= ' Text/javascript ' ></ script>
<script type= "Text/javascript" >
document.write (' <script type= ' text/javascript "src="/ Delayfile.php?url=http://localhost/js/load/2.js "><\/script>");
document.write (' <script type= "Text/javascript" src= "/delayfile.php?url=http://localhost/js/load/1.js" >< \/script> ');
Alert ("I am an internal script");

After this code has been executed, the DOM will be modified to:

The results of the code execution also conform to the order of the scripts in the DOM: "I am the first script"-> "I am the internal script"-> "I am the second script"-> "I am the first script"

[2] Only internal scripts are written to the same <script> tag via document.write:

In this case, the internal script written through Documen.write, the order of execution priority is the same as the code written in the script tag, and executed in the order in which it was written:

We then modify the HTML code as follows:

<script src= '/delayfile.php?url=http://localhost/js/load/1.js ' type= ' text/javascript ' ></script>
<script type= "Text/javascript" >
document.write (' <script type= "Text/javascript" >alert "(" I am docment.write written in the internal script ") <\/script>");
Alert ("I am an internal script");
document.write (' <script type= ' text/javascript ' >alert ("I am docment.write written internal script 2222") <\/script>);
document.write (' <script type= ' text/javascript ' >alert ("I am docment.write written internal script 3333") <\/script>);

In this case, the script written by Document.Write is considered to be the same as the code priority at the write location, so the order of the pop-up boxes in all browsers is: "I am the first script"-> "I am the document.write written internal script"-> " I am the internal script "->" I am document.write written in the internal script 2222 "->" I am document.write write the internal script 3333 "

[3] In the same <script> tag, both internal and external scripts are written by document.write:

In this case, there are some differences in different browsers:

In browsers IE9 and below: As long as the internal script written through document.write, the priority is always higher than the external script written by document.write, and the priority is the same as the code written in the tag. An external script written through document.write is always executed after the code that writes the tag is executed, followed by the sequence of writes;

And in the browser, An internal script that appears prior to the first document.write write to an external script, the order of execution has the same precedence as the script in the tag, and the script code that is written after it, whether internal or external, always waits until the script inside the tag is executed, and then executes in the order in which it was written.

We modify the code in the following HTML:

 <script src= '/delayfile.php?url=http://localhost/js/load/1.js ' type= ' text/ JavaScript ' ></script><script type= ' text/javascript ' > document.write (' <script type= ' text/ JavaScript ">alert (" I am docment.write written in internal script ") <\/script>"); Alert ("I am an internal script"); document.write (' <script type= "Text/javascript" src= "/delayfile.php?url=http://localhost/js/load/1.js" >< \/script> '); document.write (' <script type= ' text/javascript ' >alert ("I am docment.write written internal script 2222") <\/script>); document.write (' <script type= "Text/javascript" src= "/delayfile.php?url=http://localhost/js/load/1.js" >< \/script> '); document.write (' <script type= ' text/javascript ' >alert ("I am docment.write written internal script 3333") <\/script>); Alert ("I am an internal script 2222");</script> 

In browsers IE9 and below, the above code pops up with the following: "I am the first script"-> "I am document.write write the internal script"-> "I am the internal script"-> " I am document.write written by the internal script 2222 "->" I am document.write writing the internal script 3333 "->" I am the internal script 2222 "->" I was the first script "->" I was the first script "

In other browsers, the code pops up as follows: "I am the first script"-> "I am document.write written in the internal script"-> "I am the internal script"-> "I am the internal script 2222"-> "I was the first script"-> " I am document.write written in the internal script 2222 "->" I was the first script "->" I was document.write write the internal script 3333 "

If you want IE and the following browsers to behave in a consistent manner with other browsers, it is optional to take the code that introduces the internal script and put it in a new <script> tag in the back, because the back <script> The sequence of code that is introduced by document.write in the label must be followed by the code in the previous tag.

2.3 When adding code through dynamic scripting technology

The primary purpose of adding code through dynamic scripting is to create non-blocking scripts, because code added by dynamic scripting technology does not execute immediately, and we can add dynamic scripts to the page by using the following load function:

function Loadscript (url,callback) {
var script = document.createelement ("script");
Script.type = "Text/javascript";
Binding Loaded Event
if (script.readystate) {
script.onreadystatechange = function () {
if (script.readystate = = " Loaded "| | Script.readystate = = "complete") {
callback&&callback ();}}}
else{
script.onload = function () {
callback&&callback ();
}
}
script.src = URL;
document.getElementsByTagName ("Head") [0].appendchild (script);
}

However, external JavaScript scripts added through dynamic scripting are not guaranteed to be executed in the order in which they are added, which can be referred to in detail by callback or by using the HTML () method of jquery: http://www.jb51.net/article/26446.htm

2.4 Inject script through Ajax

The Ajax injection script is also one of the techniques for adding non-blocking scripts, and we first need to create a XMLHttpRequest object and implement the Get method, and then take the script content and inject it into the document through the Getting method.

code example:

We can encapsulate the XMLHttpRequest object with the following code and encapsulate its Get method:

var xhr = (function () {
function createxhr () {
var xhr;
if (window. XMLHttpRequest) {
xhr = new XMLHttpRequest ();
} else if (window. ActiveXObject) {
var xhrversions = [' msxml2.xmlhttp ', ' msxml2.xmlhttp.3.0 ', ' msxml2.xmlhttp.6.0 '], I, Len;
for (i = 0, len = xhrversions.length i < len; i++) {
try{
xhr = new ActiveXObject (xhrversions[i));
catch (E) {
}
}
}else{
throw new Error ("Cannot create xhr object");
}
return xhr;
}
function Get (url,async,callback) {
var xhr = createxhr ();
Xhr.onreadystatechange = function () {
if (xhr.readystate = 4) {
if (xhr.status >= && xhr.status < 300) | | Xhr.status = = 304) {
callback&&callback (xhr.responsetext);
} else{
alert ("Request failed with error code + xhr.status);
}}" Xhr.open ("Get", url,async);
Xhr.send (null);
}
return {
Get:get
}

Then create the Loadxhrscript function based on the XHR object:

 
 

Our above get method adds a parameter, whether asynchronous, so if we use the synchronization method, the script injected through Ajax must be executed in the order of addition, and if we adopt the asynchronous scheme, the order of execution of the added script is definitely uncertain.

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.