Analyze the JavaScript script loading and code execution sequence in the browser, and analyze the javascript

Source: Internet
Author: User

Analyze the JavaScript script loading and code execution sequence in the browser, and analyze the javascript

This article mainly analyzes the execution sequence of JavaScript scripts in HTML based on several methods of Introducing JavaScript to HTML pages.

1. Obstruction of JavaScript script execution

JavaScript is blocked when it is parsed and executed in the browser. That is to say, when JavaScript code is executed, page parsing, rendering, and download of other resources must be stopped and the script execution is complete. This is not controversial, and the behavior in all browsers is consistent, the reason is not hard to understand: the browser needs a stable DOM structure, javaScript may modify the DOM (changing the DOM structure or modifying a DOM node). If page parsing continues while executing JavaScript, the entire parsing process becomes difficult to control, parsing errors may also increase.

However, there is another issue that requires attention. For external scripts, there is also a script download process. In early browsers, the download of JavaScript files not only blocks page parsing, it even blocks the download of other resources on the page (including other JavaScript script files, external CSS files, images, and other external resources ). JavaScript download is allowed in parallel from IE8, firefox3.5, safari4, and chrome2, And the download of JavaScript files does not block the download of other resources (earlier versions, the download of JavaScript files will also block the download of other resources ).

Note: different browsers have different limits on the maximum number of connections under the same domain name. The requirements in the HTTP1.1 Protocol are not higher than two, however, most browsers currently provide more than 2 max connections, IE6/7 are both 2, IE8 is increased to 6, and firefox and chrome are also 6, of course, this setting can also be modified, detailed content can refer to: http://www.stevesouders.com/blog/2008/03/20/roundup-on-parallel-connections/

2. Script Execution Sequence

The browser parses pages in the order from top to bottom. Therefore, under normal circumstances, the execution order of JavaScript scripts is also from top to bottom, that is, the code that appears first 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. Note that we are marked with red "under normal circumstances". Why? We know that JavaScript code can be added to HTML in multiple ways, which are summarized as follows (the module loaders such as requirejs and seajs are not considered ):

(1) normal introduction: Introduce the script code or introduce external scripts through the <script> label on the page.

(2) write the <script> tag or code to the page through the document. write Method

(3) Use the dynamic script technology to create <script> elements using the DOM interface, set the src of the elements, and then add the elements to the DOM.

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

(5) write the JavaScript code directly in the event handler of the element or directly use it as the URL subject. The example is as follows:

<! -- Directly write it in the event handler of the element --> <input type = "button" value = "click to test" onclick = "alert ('click button ') "/> <! -- As the URL subject --> <a href = "javascript: alert ('dd')"> JS script as the URL subject </a>

The 5th cases have no impact on the execution sequence of the scripts we discuss, so we will only discuss the first four cases:

2.1 When a script is introduced normally

When a script is introduced normally, the JavaScript code is executed in the order from top to bottom. Whether the script is downloaded in parallel or not, it is executed from top to bottom according to the introduced sequence, the following DEMO is used as an example:

First, a script is written in PHP. This script receives two parameters, File URL and latency. The script sends the file content to the browser after the latency is passed in. The script is as follows:

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

In addition, two JavaScript files, 1.js and 2.js, are defined. In this example, the code of the two files is as follows:

1. js

Alert ("I am the first script ");

2. js

Alert ("I am the second script ");

Then, we introduce the script 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 internal script "); </script> <script src = '/delayfile. php? Url = http: // localhost/js/load/2.js& delay = 1 'Type = 'text/javascript '> </script>

Although the first script will be returned after a delay of 3 seconds, the pop-up sequence in all browsers is the same, that is: "I am the first script"-> "I am an internal script"-> "I am the second script"

2.2 When a script is written to the page through document. write

Document. when the document stream is not closed, write the content to the adjacent location after the script is completed. After the Browser executes the current short code, it will parse the document. write content.

Note: document. there is still a problem with the location where the write content is written. The content that should not appear inside the

When writing a script through document. write, there are some problems that need to be classified:

[1] In the same <script> label, only external scripts are written through document. write:

In this case, the execution sequence of external scripts is always lower than the code in the label of the introduced script, and the code is executed according to the introduced sequence. we modify the code in 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>

After the code is executed, the DOM will be changed:

The code execution result also conforms to the script sequence in the DOM: "I am the first script"-> "I am an internal script"-> "I am the second script"-> "I am the first script"

[2] In the same <script> label, only internal scripts are written through document. write:

In this case, the execution order priority of the internal scripts written through en. write is the same as that of the code written in the script tag, and is executed in the order of writing:

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 a docment. write internal script ") <\/script> '); alert (" I am an internal script "); document. write ('<script type = "text/javascript"> alert ("I Am a docment. write internal script 2222 ") <\/script> '); document. write ('<script type = "text/javascript"> alert ("I Am a docment. write internal script 3333 ") <\/script> '); </script>

In this case, document. the write script is considered to have the same priority as the code at the write location. Therefore, in all browsers, the pop-up box is in the following order: "I am the first script"-> "I am document. write internal script "->" I am an internal script "->" I Am a document. write internal script 2222 "->" I am document. write internal script 3333"

[3] when the same <script> label simultaneously writes internal scripts and external scripts through document. write:

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

In IE9 and the following browsers. the priority of an internal script written by write is always higher than that written by document. write external scripts with the same priority as the code in the write tag. The external scripts written through document. write are executed in the write order after the code written into the tag is executed;

The browser appears in the first document. the internal script before writing the external script, the execution order priority is the same as the script priority in the write tag, and the subsequent written script code, whether it is an internal script or an external script, always wait until the script in the write tag is executed and then run in the write order.

Modify the following HTML code:

<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 a docment. write 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 a docment. 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 a docment. write internal script 3333 ") <\/script> '); alert (" I am an internal script 2222 "); </script>

In IE9 and the following browsers, the content displayed after code execution is: "I am the first script"-> "I am document. write internal script "->" I am an internal script "->" I Am a document. write internal script 2222 "->" I am document. write internal script 3333 "->" I am an internal script 2222 "->" I am the first script "->" I am the first script"

In other browsers, the pop-up content after code execution is: "I am the first script"-> "I am document. write the written internal script "->" I am an internal script "->" I am an internal script 2222 "->" I am the first script "->" I Am a document. write internal script 2222 "->" I am the first script "->" I am document. write internal script 3333"

If you want IE and the following browsers to be consistent with other browsers, the optional method is to take out the Code that introduces internal scripts, put it in a new <script> label. the execution sequence of the Code introduced by write must be following the code in the previous tag.

2.3 when adding code through dynamic script technology

The main purpose of adding code through dynamic script technology is to create a non-blocking script. Because the code added through dynamic script technology is not executed immediately, we can add a dynamic script to the page through the following load function:

Function loadScript (url, callback) {var script = document. createElement ("script"); script. type = "text/javascript"; // bind the 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, the external JavaScript script added by dynamic scripting technology does not guarantee to be executed in the order of addition, this can be done through the callback or the jQuery html () method, For details, see: http://www.bkjia.com/article/26446.htm

2.4 Ajax injection script

Using Ajax injection scripts is also one of the technologies for adding non-blocking scripts. First, we need to create an XMLHttpRequest object and implement the get method. Then, we can use the get method to obtain the script content and inject it into the document.

Sample Code:

We can use the following code to encapsulate the XMLHttpRequest object 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 ("xhr object cannot be created");} return xhr;} function get (url, async, callback) {var xhr = createXhr (); xhr. onreadystatechange = function () {if (xhr. readyState = 4) {if (xhr. status >=200 & xhr. status <300) | xhr. status = 304) {callback & callback (xhr. responseText);} else {alert ("request failed, 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:

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); });} 

We added a parameter in the get method above, that is, whether it is asynchronous. If we adopt the synchronous method, the scripts injected through Ajax must be executed in the order of addition. Otherwise, if we adopt an asynchronous scheme, the execution sequence of the added scripts cannot be determined.

Articles you may be interested in:
  • JavaScript comprehensively parses the JavaScript execution sequence in various browser web pages
  • JavaScript Execution patience in various browsers
  • Simple Example of Javascript script execution sequence in Html
  • The execution sequence of multiple events bound to javascript attachEvent
  • How to ensure in-depth analysis of JavaScript Execution sequence jquery.html
  • How to ensure that the execution order of JavaScript jquery.html is not the omnipotent key
  • How to ensure the execution sequence of JavaScript
  • Solution: JS setTimeout Function incompatibility failure and not execution in Firefox browser
  • Introduction to the execution sequence of Javascript code During page loading
  • How to control the execution sequence of callback functions of js asynchronous operations
  • The sequence of javascript parsing execution varies in different browsers.
  • When js determines that the browser type is ie6, It is not executed.

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.