[] On javaScript script tag defer and async

A, async and defer the definition

Take a look at their definition of async and defer it, turn the telescope Little Red Book, is the introduction of so

1.1 defer

The use of this attribute indicates that the script is in the implementation will not affect the structure of the page. That is, the script will be delayed until the entire page are parsed completely before running. Therefore, in the <script>setting element defer property, the equivalent of telling the browser to download immediately, but deferred execution.

HTML5 specifications script executed in the order in which they appear, so the first delay script will first execute the second delay script, and both scripts prior to DOMContentLoadedexecution event. In reality, the script will not necessarily delay the implementation of the order, not necessarily at DOMContentLoadexecution time before the trigger, it is best to include only a delay script.

About DOMContentLoadedthe event does not understand can read the MDN, and there are examples Detailed presentation >>> [DOMContentLoaded] (https: // de veloper.mozilla.org/zh-CN/docs/Web/API/Document/DOMContentLoaded_event)

1.2 async

This property is defersimilar to the process are used to change the behavior of the script. Likewise with the defersimilar, asyncit applies only to an external script file, and tells the browser to download files immediately. But the deferdifference is marked as asyncthe script does not guarantee execution according to their order.

The second script files may be executed before the first script file. So make sure and do not depend very important between the two. Specify the asyncpurpose of the property is not to wait for a page to download and execute two scripts, so the page is loaded asynchronously other content.

In summary, these two properties is the script tag will cause the asynchronous loading, but the timing of the execution is not the same. A reference to a map on the segmentfault the answer
Here Insert Picture Description
Blue line represents the network read, the red line represents the execution time, maybe for all scripts; green line represents the HTML parsing HTML gray line represents the block time, maybe all show DOM rendering state;

That asyncis out of order, and deferthe implementation of the order, which also determines the asynccomparative analysis applies to Baidu or Google this type of analysis does not depend on other libraries script. From the figure can be seen a normal <script>load and parse labels are synchronized and can block DOM rendering, which is what we often will <script>write <body>one of the reasons the bottom, in order to prevent the loading of resources caused by prolonged black and white, another reason might be that js DOM manipulation, so to perform all DOM finished rendering before.

1.3 is really the case?

However, this figure (almost the only answer to the search) is not rigorous, this is only the case specifications, most browsers will be made in the realization of optimization.

↓ chrome look at how it is done

"WebKit technology insider":

  1. When the user enters the web page URL, WebKit calls its resource loader loads the page corresponding to the URL.

  2. Loading module relies on a network connection is established, send the request and receive the responses.

  3. WebKit received data or various web resources, some resources may be synchronous or asynchronous acquisition.

  4. HTML pages were handed over to the interpreter into a series of words (Token).

  5. Construction interpreter node (Node) The words, formed DOM tree.

  6. If the node is the JavaScript code, then call the JavaScript engine interpret and execute.

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

  8. If the node need to rely on other resources, such as images, CSS, video, call the resource loader to load them, but they are asynchronous, and will not hinder continue creating the current DOM tree; if it is JavaScript resource URL (not marked asynchronously) , you need to stop creating the current DOM tree until the JavaScript resources JavaScript engine load created and continue to execute after the DOM tree.

So, popular terms, chrome browser will first request the HTML document, and then call the appropriate resources where the resource loader asynchronous network requests, DOM rendering the same time, until it encounters <script>when label, the main process will stop rendering waiting for this resource is loaded and then call the V8 engine to parse js, then proceed DOM parsing. I understand if the rate of the asyncproperty is equivalent to open a separate process to separate loaded and executed, and deferis and will be <script>placed in <body>the bottom of the same effect.

Second, the experimental situation as

2.1 demo

In order to verify the above conclusion we have to test

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <link href="http://libs.baidu.com/bootstrap/3.0.3/css/bootstrap.css" rel="stylesheet">
        <link href="http://cdn.staticfile.org/foundation/6.0.1/css/foundation.css" rel="stylesheet">
        <script src="http://lib.sinaapp.com/js/angular.js/angular-1.2.19/angular.js"></script>
    	<script src="https://cdn.bootcss.com/underscore.js/1.9.1/underscore.js"></script>
        <script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
    </head>
    <body>
        ul>li{这是第$个节点}*1000
    </body>
    </html>

A simple demo, cites two months CSS3 JS from each CDN, the body which created 1000 li. It refers to the resource and related properties added by adjusting external use chrome verify Timeline.

2.2 placed <head>within

Here Insert Picture Description
Asynchronous loading of resources, but will block <body>the rendering will be black and white, in order to execute the script immediately

2.3 placed at <body>the bottom of the

Here Insert Picture Description
Asynchronous loading of resources, such as <body>the content rendering is completed and loaded the JS execution order

2.4 is placed in <head>the head and usingasync

Here Insert Picture Description
Asynchronous loading of resources, and finished loading JS resources to implement immediately, and not in order, who fast on who should

2.5 is placed in <head>the head and usingdefer

Here Insert Picture Description
Asynchronous loading of resources, then after the order of execution after JS DOM rendering

2.6 is placed in <head>the head and use asyncanddefer

Here Insert Picture Description
Performance and asyncconsistent, opened a hole in the brain, these two attributes to exchange position, will not have to see the effect of coverage found is consistent = =

In summary, the webkit engine , the recommended way is still to <script>write at <body>the bottom, you can use if you need to use Baidu Google Analytics or no garlic and other independent library asyncproperty, if your <script>label must be written on <head>the head can be used defer property

Third, compatibility

On caniuse, asyncin IE <= 9 does not support other browsers OK; deferin IE <9 support but there will be bug =, other browsers OK; the phenomenon is described in this issue, which is the "telescope" in the recommendations only one deferof the reasons. So both attributes are specified in order to asyncenable time is not supported defer, but deferin some cases still have bug.

The defer attribute may be specified even if the async attribute is specified, to cause legacy Web browsers that only support defer (and not async) to fall back to the defer behavior instead of the synchronous blocking behavior that is the default.

Conclusions

  • asyncApplies only to the chain, the provisions of asynchronous execution script
    - does not block the download page parsing
    - will not be executed in order of appearance, first download is complete which will be executed first
    - time execution, it is possible not parsed page
  • deferApplies only to the chain, delayed the implementation of the provisions of the script
    - does not block the page parsing
    - executed before DOMContentLoaded html parsing after completion
    - will be executed in order of appearance

In fact, so to speak, the safest way is to <script>write at the <body>bottom, there is no compatibility issues, no black and white issue, there is no execution order problems, sit back and relax, not to engage in any deferand asyncflowers friends ~

Published 134 original articles · won praise 80 · views 30000 +

Guess you like

Origin blog.csdn.net/Umbrella_Um/article/details/104916754