High-performance JavaScript (1)

Source: Internet
Author: User
Tags blank page

The first part loads and runs

When the browser encounters a <script> tag, as in the HTML page above, it is impossible to predict whether or not JavaScript will add content to the <p> tag. Therefore, the browser stops, runs this JavaScript code, and then continues parsing and translating the page. The same thing happens in the process of loading JavaScript using the SRC attribute. The browser must first download the code for the external file, which takes some time, and then resolves and runs the code. In this process, page parsing and user interaction are completely blocked.

To maintain the similarity of the code, we try to organize the same code together, for example:

One obvious performance problem with these seemingly more structured code is that three JavaScript files are loaded in the . The user has to endure this perceptible delay. keep in mind that the browser does not render any part of the page until it encounters the <body> tag . placing the script at the top of the page in this way results in a perceptible delay, usually shown as a blank page that is displayed first when the page is opened, while the user cannot read or interact with the page. to better understand this process, we use waterfall diagrams to depict the download process for each resource. Figure 1-1 shows the process of downloading each script file and style sheet file during page loading.

The first JavaScript file starts to download and blocks the download process for other files. Further, there is a delay before file1.js download and file2.js start downloading, which is the time required for the file1.js to run completely. Each
The file must wait until the previous file has been downloaded and finished before it can begin its own download process. When these files are downloaded, the user faces a blank screen. This is the behavior pattern of most browsers today. Internet Explorer 8, Firefox 3.5, Safari 4, and Chrome 2 allow JavaScript files to be downloaded in parallel. The good news is that when an <script> tag is downloading external resources, it does not have to block other <script> tags. Unfortunately, JavaScript downloads still have to block the download process for other resources, for example. Even if the download process between scripts is not blocked, the page still waits for all JavaScript code to download and execute before proceeding. Therefore, the problem is not fully resolved when the browser improves performance by allowing parallel downloads. Because the script blocks the download process for other page resources, it is recommended that all <script> tags be placed as close to the bottom of the <body> tag as possible, minimizing the impact on the entire page download . For example

This code shows the location of the recommended <script> tags in the HTML file. Although script downloads are blocked from one another, the page is downloaded and displayed in front of the user, and the speed of the page does not appear too slow. This is the first law of the "Yahoo! Superiority group" on javascript: Put the script at the bottom.

In addition, the browser requests 4 25K external JS file speed is slower than the request 1 100K JS file, therefore, we should try to include the JS file in one load. (each HTTP request will incur an additional performance burden, download
A 100KB file is faster than downloading four 25KB files).

1.1 nonblocking Scripts non-blocking script

Deferred Scripts Deferred Script

HTML 4 defines an extended property for the <script> tag: defer. This defer property indicates that the script contained in the element is not intended to modify the DOM, so the code can be executed later. The Defer property is supported only by Internet Explorer 4 and Firefox 3.5 's later browsers and is not an ideal cross-browser solution. On other browsers, the defer property is ignored,<script> tags are handled by default (causing blocking). This approach is still a useful solution if the browser supports it. Examples are as follows:


<script type= "Text/javascript" src= "File1.js" defer></script>

A <script> tag with the defer attribute can be placed anywhere in the document. The corresponding JavaScript file will start the download when <script> is solved, but the code will not be executed until the DOM load is complete (before the OnLoad event handle is called). When a defer JavaScript file is downloaded, it does not block other browser processes, so these files can be downloaded in parallel with other resources on the page. (It should be understood that the execution time of a <script> script consists of two parts, (1) The Request load time (2) JS execution time. The function of defer is to delay the execution time of JS. Any <script> element with the defer attribute will not be executed until the DOM is loaded, both inline and external script files. The following example shows how the defer property affects script behavior.

The code pops up three dialog boxes during page processing. If the browser does not support the defer property, the order in which the dialog box pops up is "defer", "script", and "load". If the browser supports the Defer property, then the order of popup dialogs is "script", "defer" and "load". Note that the <script> element labeled defer is not running after the second, but is called before the OnLoad event handle is processed .

Dynamic SCRIPT Element Elements

The Document Object Model (DOM) allows you to dynamically create almost all of the document content of HTML using JavaScript. The root of this is that the,<script> element is no different from the other elements of the page: reference variables can be retrieved through the DOM and can be moved, deleted, or created from the document. A new <script> element can be easily created by standard DOM functions

var script = document.createelement ("script"); Script.type = "Text/javascript"; SCRIPT.SRC = "File1.js"; Document.getelementsbytagname_r ("Head") [0].appendchild (script);

The new <script> element loads the file1.js source file. This file starts downloading immediately after the element is added to the page . The point of this technique is that no matter where the download is initiated, the download and operation of the file does not block other page processing processes .

You can even put the code in the

In most cases, you want to invoke a function to implement the dynamic loading of a JavaScript file. The following function encapsulates the functionality required by the standard implementation and IE implementations:

function Loadscript (URL, callback) {  var script = document.createelement ("script")  Script.type = "text/ JavaScript ";  if (script.readystate) {//ie   script.onreadystatechange = function () {   if (script.readystate = = "Loaded" | | Script.readystate = = "complete") {   script.onreadystatechange = null;   Callback ();   } };  } else {//others   script.onload = function () {   callback ();};  }  script.src = URL;  Document.getelementsbytagname_r ("Head") [0].appendchild (script); }
1.2 XMLHttpRequest Script Injection XHR scripting injection

Another way to get a script in a non-blocking way is to use the XMLHttpRequest (XHR) object to inject the script into the page. This technique first creates a Xhr object, then downloads the JavaScript file, and then injects the JavaScript code into the page with a dynamic <script> element. The following is a simple example:

var xhr = new XMLHttpRequest (); Xhr.open ("Get", "File1.js", true); Xhr.onreadystatechange = function () {  if (xhr.readystate = = 4) {  if (xhr.status >= && xhr.status < ; 300 | | Xhr.status = = 304) {  var script = document.createelement ("script");  Script.type = "Text/javascript";  Script.text = Xhr.responsetext;  Document.body.appendChild (script);  }  } }; Xhr.send (NULL);

This code sends a GET request to the server to get the File1.js file. The onReadyStateChange event handler checks whether the readystate is 4, and then checks that the HTTP status code is not valid (2XX indicates a valid response, and 304 represents a cached response). If a valid response is received, a new <script> element is created and its Text property is set to the ResponseText string received from the server. Doing so will actually create a <script> element with inline code. Once the new <script> element is added to the document, the code is executed and ready to be used.

The main advantage of this approach is that you can download JavaScript code that is not executed immediately. Since the code is returned outside of the <script> tag (in other words, not constrained by the <script> tag), it is not automatically executed after downloading, which allows you to postpone execution until everything is ready. Another advantage is that the same code does not throw an exception in all modern browsers. The main limitation of this approach is that JavaScript files must be placed in the same domain as the page and cannot be downloaded from CDNs (CDN refers to "content Delivery network", as mentioned in the previous 002 section, "Group Scripts"). For this reason, large web pages typically do not use XHR script injection technology.

1.3 Recommended nonblocking pattern recommended non-blocking mode

The recommended way to load a large amount of JavaScript into a page is in two steps: The first step is to include the code required to load the JavaScript dynamically, and then load the part of the page that you want to initialize in addition to the JavaScript. This part of the code is as small as possible and may contain only the Loadscript () function, which is downloaded and run very quickly and does not cause much disruption to the page. When the initial code is ready, use it to load the rest of the JavaScript.
For example:

<script type= "Text/javascript" src= "loader.js" ></script> <script type= "Text/javascript" >  Loadscript ("The-rest.js", function () {  application.init ();  }); </script>

Place this code before the body's close label </body>. There are several advantages to this: first, as discussed earlier, this ensures that JavaScript runs without affecting the rest of the page display. Second, when the second part of the JavaScript file completes the download, all the necessary DOM for the application is created and ready to be accessed, avoiding the use of additional event handling (such as window.onload) to know if the page is ready.

1.4 The Lazyload library && the LABJS library

As a more versatile tool, Yahoo! Search's Ryan Grove created the Lazyload library (see http://github.com/rgrove/lazyload/). Lazyload is a more powerful loadscript () function. The lazyload is only about 1.5KB after finishing (fine-shrinking, not gzip-compressed). Please refer to the detailed documentation for details on how to use it.

Another non-blocking JavaScript loading library is LABJS (http://labjs.com/), an open source library written by Kyle Simpson, sponsored by Steve Souders. This library takes finer control of the loading process and attempts to download as much code as possible in parallel. LABJS is also quite small, only 4.50KB (lean, not gzip compressed), so it has the smallest page code size

Summary

Managing JavaScript code in the browser is a tricky issue because code execution blocks other browser processing, such as drawing with the interface. each time you encounter a <script> tag, the page must stop waiting for the code to download (if it is external) and execute it before proceeding with the rest of the page . However, there are several ways to reduce the impact of JavaScript on performance:

[1] Place all <script> tags at the bottom of the page, immediately above the body close tag </body>. This method ensures that the page resolves before the script runs.

[2] Package the script as a group. With fewer <script> tags on the page, the page loads faster and responds more quickly. This is true regardless of the external script file or inline code.

[3] There are several ways to download JavaScript using non-blocking methods:
--Add defer attribute for <script> tag (only for Internet Explorer and Firefox 3.5 or later)
--Create <script> elements dynamically, use it to download and execute code
--Download the code with the XHR object and inject it into the page

More referance

Http://coolshell.cn/articles/9749.html

High-performance JavaScript (1)

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.