JavaScript load without blocking and defer, async

Source: Internet
Author: User
Javascript has the blocking feature. When a Browser executes Javascript code, it cannot do other things at the same time. When downloading JavaScript, all browsers will block all other activities, such as downloading other resources, content presentation. After downloading, parsing, and executing JavaScript code, you can continue to download other resources and present the content in parallel. Load without blocking

Put js in the head. How does the browser execute it? Is it loaded in order or in parallel? In the old browser, all the files are loaded sequentially, which ensures that the loaded js dependency will not be faulty. However, a few new browsers have begun to allow parallel loading of js files. That is to say, JavaScript files can be downloaded at the same time, but the files are executed in sequence.

The download process is asynchronous, but it is synchronized when javascript is executed. The script tag that appears first must be executed first, even if it is downloaded in parallel, the last download is complete, unless the script tag is marked with defer. Any javascript will interrupt the parsing of the current html document during execution, which will naturally prevent page rendering.

Loading javascript will not affect the rendered pages, but it will interrupt html document parsing. the browser will decide whether to re-render the current document or re-Rename the document after javascript Execution. Therefore, even if javascript is placed at the end of the page, the browser will be suspended, but it does not affect the dom documents that have been parsed before. This is feasible for users.

After javascript is downloaded, it is executed immediately. All javascript Execution will block other behaviors of the browser, such as blocking other javascript Execution, other http request execution, and page parsing and rendering. (The download of external js in the html document also blocks the browser's behavior, but the download of dynamic js by creating the script element will not, It may be thought that dynamic js will not change the page effect, therefore, concurrent resource downloads are allowed .)

Dynamic script download

The UI thread loads resources based on the order in which resources (resources refer to css files, images, and so on) are written on the page. Loading resources means that resources are obtained using http requests, such as css external files, the processing of html files, images, and other resources http requests means that the resource loading is complete. However, the loading process of external javascript files is divided into two steps, the first step is to execute an http request to download an external js file, just like loading a css file and an image. However, after javascript completes the http operation, it does not mean that the operation is complete. The UI thread will then execute it. The download and execution of js scripts must be a complete operation and cannot be separated. Dynamic js download will not be blocked, but the execution will certainly.

To improve the user experience, the browser cannot avoid accelerating the execution of the UI thread, but the download and execution of splitting Javascript is not feasible, this means that multiple resources can be downloaded at the same time.

Place common and stable static resources on a static resource server and provide them externally by a unified domain name. This domain name must be different from the domain name requested by the subject, the principle is that the browser only limits the number of connections through the domain name. If a page contains two different domains, the number of concurrent http requests will also be doubled. Yes, it requires overhead for DNS resolution, so the two are the best.

All external js Code is divided into the UI initialization code and other code. The UI initialization code is the code executed during page loading. Load and execute js code that will not be used for page initialization and display. The onload event is triggered after the browser busy instructions are completed, that is, execute js scripts irrelevant to page loading in the onload method.

The core technology of script Loading without blocking is to dynamically create the dom node of the script and allow cross-origin access.

var script=document.createElement("script");script.type="text/javascript";script.src="file.js";document.getElementsByTagName("head")[0].appendChild(script);

Dynamic script elements, that is, the script tag is generated by the existing script instead of being written to HTML, because the script tag is also a DOM element, javaScript allows DOM operations through DOM APIs. The dynamic script starts to be downloaded only when the newly created script element is added to the html document. It is executed immediately after the download.

The advantage of a non-blocking script is that it does not block the execution of the UI, nor affect the execution of other synchronized js Code. Blocking scripts change the script loading sequence, therefore, when using a non-blocking script, you must pay more attention to the dependency between the scripts to ensure that the scripts on the entire page can be executed normally.

When no blocking script is used, it does not matter whether the code is placed at the head label or at the bottom of the html document.

The total time of page loading is not the standard for measuring the speed of page loading. The time for Synchronous blocking loading of pages is the accurate standard for measuring the page loading efficiency. Non-blocking Script Loading may increase the loading time of the entire page, however, it can reduce the page blocking loading time.

The asynchronous execution of the script will cause the issue of pre-and post-dependency. After the script is loaded and executed, non-ie browsers will trigger the onload event of the script element. The onreadystatechange event exists in IE browser, and we can put the callback in this event for processing.

When the browser parses the script tag (whether embedded or external), the browser downloads, parses, and executes the javaScript code in the tag first, the download and rendering of all subsequent page content are blocked. (That is to say, the download of external js will also block other threads. Currently, a few browsers support parallel download of js)

The core of the script loading technology without blocking is that when the js script is downloaded dynamically, the execution of the UI thread is not blocked. Why does dynamic scripts not block ui threads? It may be because the browser believes that dynamic resources will not affect page rendering.

Two attributes that make the script latency and Asynchronization: defer and async

The js script changes the content of the document input stream, so the page rendering will be paused when Javascript is executed. There is no problem with Inline scripts because the scripts and html documents are loaded at the same time. However, the download of external scripts (depending on the network speed) also blocks the parsing and rendering of browser documents, it may even Block Some browsers from downloading other resources (currently Some browsers have implemented parallel download ). So the defer and async attributes appear to optimize the display of the page.

Defer (latency) is defined in html4.0. This attribute allows the browser to delay the download of scripts. After the document is loaded and parsed, download and parse the documents in the order they appear. That is to say, the "script" of the defer attribute is similar to the effect of placing the "script" at the bottom of the body and will be executed before the DOMContentLoaded event of the document.

Placing the script at the bottom of the body is better than adding the defer attribute to the script to delay loading.

Async (asynchronous) is a new attribute of HTML5. This attribute enables the browser to download scripts in parallel without blocking the parsing and rendering of the browser's documents. After the download is complete, the script is executed immediately, execution may be unordered, depending on the download completion time)

If the browser supports both of the preceding attributes and the script tag has these attributes, The async attribute takes effect better than defer.

In browsers that do not support the async attribute, You can dynamically create a script element and insert it into the document to asynchronously load and execute the script:

Requirejs is implemented using this method.

For more articles about JavaScript load without blocking and defer and async, please pay attention to PHP!

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.