Code execution sequence of JavaScript script loading and execution in browser environment

Source: Internet
Author: User
Tags file url script tag

This article is based on several ways of introducing JavaScript to HTML pages, analyzing the order of execution of JavaScript scripts in HTML

1. About the blocking of JavaScript script execution

JavaScript is blocked when parsed and executed in the browser, that is, when the JavaScript code executes, the parsing of the page, rendering, and downloading of other resources are stopped waiting for the script to complete ①. This is uncontroversial, and the behavior in all browsers is consistent, and the reason is not difficult to understand: the browser needs a stable DOM structure, and JavaScript may modify the DOM (change the DOM structure or modify a DOM node), If the parsing of the page continues while the JavaScript is executing, the entire parsing process becomes unmanageable, and the parsing error can become significant.

However, there is another problem to note, for external scripts, also involves a script download process, in the early browser, the download of JavaScript files will not only block the page parsing, and even block the page other resources download (including other JavaScript script files, external CSS files and external resources such as pictures). Starting with IE8, firefox3.5, Safari4, and chrome2 allows JavaScript to be downloaded in parallel, while the download of JavaScript files does not block the download of other resources (in older versions, The download of JavaScript files also blocks the download of other resources).

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

2. Order of execution of scripts

Browsers parse pages from top to bottom, so JavaScript scripts are normally executed from top to bottom, that is, code that appears first on the page, or code that is first introduced, is always executed first. This is true even when JavaScript files are allowed to be downloaded in parallel. Note that we are red in the "normal circumstances", why? We know that there are several ways to add JavaScript code in HTML, as outlined below (regardless of module loaders such as Requirejs or SEAJS):

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

(2) Write <script> tag or code to page by document.write method

(3) Using the dynamic scripting technique, the DOM interface is used to create the <script> element, and the src of the element is set, and then the elements are added into the DOM.

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

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

<!--written directly in the element's event handlers-- <  type= "button"  value= "Click to test"  onclick= "alert (' click button ')"  /><!--as the main body of the URL--<href= "javascript: Alert (' dd ') '>js Script as the principal of the URL </a>

The 5th scenario has no effect on the order in which we are discussing the script execution, so we will only discuss the first four cases here:

2.1 When a script is introduced normally

When a script is introduced normally, the JavaScript code executes from top to bottom, regardless of whether the script is downloaded in parallel, executed from top to bottom in the order in which it was introduced, and we use the following demo as an example:

First, write a script through PHP, the script receives two parameters, file URL and delay time, the script will send the file content to the browser after the incoming delay time, the script is as follows:

<?php$url = $_get[' url ']; $delay = $_get[' delay '];if (isset ($delay)) {sleep ($delay);} Echo file_get_contents ($url);? >

We also 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 a second script");

Then we introduce script code in the 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><script src= '/ Delayfile.php?url=http://localhost/js/load/2.js&delay=1 ' type= ' Text/javascript ' ></script>

Although the first script is delayed 3 seconds to return, in all browsers, the order of the popup is the same, namely:"I am the first script" , "I am the internal script", "I am the second script"

2.2 When writing scripts to pages through document.write

document.write when the document flow is not closed, the content is written to the location immediately after the end of the script, and the browser executes the current short code, and then parses the content written by document.write.

Note: There is also a problem with the location where the document.write is written, and the inclusion of content that should not appear inside the

There are some problems when writing scripts through document.write, which need to be categorized for illustration:

[1] Only the external script is written by document.write in the same <script> tag:

In this case, the execution order of the external script is always lower than the code in the tag that was introduced into the script , and executes in the order introduced, and 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");</script>

Once this code is executed, the DOM will be modified to:

The result of the code execution also conforms 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 thefirst script "

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

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

We will 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 the internal script written by Docment.write ") <\/script> ');        Alert ("I am an internal script");        document.write (' <script type= "Text/javascript" >alert ("I am docment.write write internal script 2222") <\/script> ');        document.write (' <script type= "Text/javascript" >alert ("I am docment.write write internal script 3333") <\/script> '); </script>

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

[3] When writing both internal and external scripts through document.write in the same <script> tag :

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, its priority is always higher than Document.Write writes the external script, and the priority is the same as the code in the write tag. External scripts written by document.write are always executed in the order in which they are written, after the code that writes the tags is executed;

In the browser, the internal script that precedes the external script written by the first document.write is given the same precedence as the script in the write tag , and script code written later, whether internal or external, will always wait until the script in the write tag finishes executing and then 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 an internal script written by Docment.write ") <\/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 write 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 write internal script 3333") <\/script> '); Alert ("I am an internal script 2222"); </script> 

In IE9 and the following browser, the above code is executed after the content is: "I am the first script," "I am theinternal script written by document.write", "I am internal script", " I'm document.write. Internal script written 2222 "I am the internal script written by document.write 3333", "I am thefirst script 2222"- >"I am the first script"

In other browsers, the code pops up after execution: "I am the first script", "I am theInternal script written by document.write", "I am an internal script ," I am the internal script 2222"," I am thefirst script,"I am the internal script written by document.write 2222" I am the first script, "--" I am document.write write internal script 3333 "

If you want IE and the following browsers to behave in a consistent manner with other browsers, then the alternative is to take the code that introduces the internal script and put it in a new <script> tag in the back, because later <script> The Code execution order introduced by document.write in the tag is definitely behind the code in the previous tag.

2.3 When adding code with dynamic scripting technology

The main purpose of adding code through dynamic scripting techniques is to create a nonblocking script, because the code added by dynamic scripting technology is not executed immediately, and we can add dynamic scripting to the page with the following load function:

function Loadscript (url,callback) {    var script = document.createelement ("script");    Script.type = "Text/javascript";    Bind 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 with dynamic scripting techniques are not guaranteed to be executed in the order they were added, which can be referred to in the callback or using jquery's HTML () method, as detailed in the following: http://www.cnblogs.com/sanshi/ Archive/2011/02/28/1967367.html

2.4 Injecting scripts through Ajax

Injecting scripts via Ajax is also one of the techniques for adding non-blocking scripts, we first need to create a XMLHttpRequest object, implement the Get method, and then get the script content and inject it into the document by getting the 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 Activexobjec                T (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 >= &&amp ; 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, based on the XHR object, create the Loadxhrscript function:

function Loadxhrscript (Url,async, callback) {    if (async = = undefined) {        async = true;    }    Xhr.get (url,async,function (text) {        var script = document.createelement ("script");        Script.type = "Text/javascript";        Script.text = text;        Document.body.appendChild (script);    });}

Our Get method above adds a parameter, that is, whether it is asynchronous, then if we take the synchronous method, the script injected via Ajax must be executed in the order of addition, whereas if we adopt an asynchronous scheme, the order of execution of the added script is definitely not deterministic.

Code execution sequence of JavaScript script loading and execution in browser environment

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.