On the defer and async attributes _javascript skills in script tags

Source: Internet
Author: User
Tags html interpreter script tag

First, the preface

See the predecessors wrote the code as follows

<script src= "#link (" Xxxx/xx/home/home.js ")" type= "Text/javascript" Async defer></script>

Unexpectedly at the same time async and defer attributes, thinking that the old driver must be what black technology, two together will certainly happen what magical chemical reaction, so hurriedly with a reverence heart to turn over the book document, first review their respective definitions.

Second, investigate

Let's look at the async defer definition and open the Little Red Book telescope.

2.1 Defer

The purpose of this property is to indicate that the script does not affect the construction of the page when it is executed. That is, the script is deferred until the entire page is parsed and then run. Therefore, setting the property in the <script> element defer is equivalent to telling the browser to download it immediately, but delaying execution.

The HTML5 specification requires that the scripts be executed in the order in which they appear, so that the first delay script executes before the second delay script, which is executed before the DOMContentLoaded event. In reality, delay scripts do not necessarily execute sequentially, and do not have to be DOMContentLoad executed before the time is triggered, so it is best to include only a delay script.

2.2 Async

This property defer , like this, is used to change the behavior of the processing script. Similarly defer , async applies only to external script files and tells the browser to download the files immediately. However defer , unlike the scripts that are marked, async they are not guaranteed to be executed in their order of precedence.

The second script file may be executed before the first script file. It is therefore important to ensure that the two are not dependent on each other. asyncThe purpose of the specified property is to not allow the page to wait for two scripts to download and execute, thus asynchronously loading the other content of the page.

Generally speaking, both of these properties cause the script tag to load asynchronously, but the timing of the execution is different. Refer to a figure in one of the answers on Segmentfault

The Blue line represents the network read, the red line represents the execution time, both are for the script, and the Green Line represents HTML parsing.

In other words, it async is disorderly, but defer sequential execution, which also determines the async more applicable to Baidu analysis or Google analysis of such a library does not rely on other scripts. You can see from the diagram that a normal <script> label loading and parsing are synchronized, blocking DOM rendering, which is one of the reasons we often <script> write at the <body> bottom, in order to prevent the load of resources caused by the long white screen, another reason is that JS may be the DOM operation , so it's done after the DOM is all rendered.

2.3 Really?

However, this picture (almost the only answer Baidu has found) is not rigorous, this is only a normative situation, most browsers in the implementation of the optimization will be made.

Let's see what Chrome does.

"WebKit Technology Insider":

1, when the user enters the URL of the Web page, WebKit calls its resource loader to load the URL corresponding to the page.

2, the loader relies on the network module to establish the connection, send the request and accept the reply.

3, WebKit received a variety of web pages or resources of data, some of which may be synchronized or asynchronous acquisition.

4, the Web page has been handed over to the HTML interpreter into a series of words (Token).

5. The Interpreter constructs nodes (node) according to words and forms a DOM tree.

6, if the node is JavaScript code, invoke the JavaScript engine to interpret and execute.

7, JavaScript code may modify the structure of the DOM tree.

8, if nodes need to rely on other resources, such as pictures, CSS, videos, etc., call the resource loader to load them, but they are asynchronous and do not hinder the continuation of the current DOM tree; If it is a JavaScript resource URL (not marked asynchronously), you need to stop the creation of the current DOM tree. The creation of the DOM tree continues until the JavaScript resource loads and is executed by the JavaScript engine.

So, in layman's terms, the Chrome browser will first request the HTML document, and then invoke the appropriate resource loader for the various resources to make asynchronous network requests, while Dom renders, until the <script> tag is encountered, The main process stops rendering until the resource is loaded and then calls the V8 engine to parse JS, and then continues with Dom parsing. My understanding if adding attributes is async equivalent to opening a separate process to load and execute independently, defer it is the same effect that will be <script> placed at the <body> bottom.

Third, the experiment

3.1 Demo

To verify the above conclusions, let's test

<! DOCTYPE html>
 
 

A simple demo, from each CDN cited 2 CSS3 JS, in the body created 1000 li. Use Chrome's timeline for validation by adjusting the location of external referencing resources and adding related properties.

3.2 Placed in

Load resources asynchronously, but blocking <body> render will appear in white screen, execute script immediately

3.3 Placed at <body> bottom


Load the resource asynchronously, and <body> the contents of the content are rendered and the finished load is executed in sequence JS

3.3 Place in

Load the resource asynchronously, and load the JS resource to execute immediately, and not in order, who fast who first

3.4 Place in


Load resources asynchronously, and then execute JS sequentially after Dom renders

3.5 Place in


Performance and async consistent, opened a brain hole, the two properties exchange position, see will have coverage effect, the results found to be consistent = =,

In summary, under the WebKit engine, the recommended way is still to <script> write at the <body> bottom, if you need to use Baidu Google Analytics or a separate library such as garlic can use async properties, if your <script> label must be written in defer Property

Iv. compatibility

So, try to figure out the psychology of the predecessors, at the same time write what is the reason, compatibility?

On Caniuse, async not supported in ie<=9, other browser OK, defer support in ie<=9 but there will be bugs, other browser OK, the phenomenon is described in this issue , which is the "telescope" suggested only one defer reason. So all two properties are specified to be async enabled when not supported defer , but defer in some cases there are bugs.

The defer is specified even if the async attribute is specified, to cause legacy WEB browsers ORT defer (and not async) to fall "defer behavior instead of the synchronous blocking Ult.

V. Conclusion

In fact, the most prudent way to <script> write at the <body> bottom, there is no compatibility issues, no white screen problems, no implementation sequence problems, rest assured, do not make what defer and async flowers ~

At present, only the webkit of Chrome's rendering mechanism, Firefox and IE are still to be studied, pictures and CSS and other external resources of the rendering needs to be studied.

Summarize

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring certain help, if you have questions you can message exchange.

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.