Deep contrast of defer and async in HTML5

Source: Internet
Author: User
Tags event listener html page script tag sleep

In the Site page, usually need to introduce external JS resources, but external JS resources may cause DOM blocking, affecting the speed of page loading. By asynchronous or delay the execution of JS, you can refer to the external JS resources without blocking the DOM. The usage is to use defer and async directly in the script tag, so what's the difference between them two?

Literally, defer is a delay, while Async is asynchronous (asynchronous). This explains that the defer and Async:defer properties are a Boolean property, and when this property exists, the script that it specifies executes 1 after the page parsing; Async is also a Boolean property, and when this property exists, it executes 2 asynchronously as long as the script is available. A more detailed explanation of the script tag is shown in the Firefox developer Center.

The concept is hard to figure out, and here is my experiment with external reference tags using different attributes to simulate an external JavaScript script in PHP:

<?php
Header ("CONTENT-TYPE:TEXT/JAVASCRIPT;CHARSET=UTF-8;");
Sleep (2);
?>
Console.log ("This is the Script");
The front page code is as follows:

<! DOCTYPE html>
<meta charset= "UTF-8" >
<script src= "./js.php" defer></script>
<!--defer and async tests for the above introduced scripts-->
<body>
This is the Document.
</body>


The following two pictures are the timeline using defer and async:

Using the Defer timeline

Note that the Blue timeline is domcontentloaded time, you can see the domcontentloaded event using defer after the JS script is executed, and async is after the HTML document is parsed, the same place is printed out "this Is the same as the time of the Script. Why is that?

We know that if the JavaScript introduction script neither uses defer nor async, the entire page must be loaded after the introduction of the script download has completed. According to the previous concept, defer is deferred execution, and async is executed asynchronously. The biggest difference between them is that the defer execution time is after the HTML document is parsed, and the execution time of the async is indeterminate, as long as the script is downloaded, it executes; the same point between them does not block the loading of other elements. If there are multiple external scripts on a page that use the Defer property, they are executed sequentially.

Application of defer and async

Because defer will execute after the page parsing completes, when the JS script runs, the page is already resolved state, this time can do DOM operation, and if not using defer, the document's state is uncertain, so can not operate. As in the above code, if you change the js.php to the following code, open the previous page and find that the content will be changed:

<?php
Header ("CONTENT-TYPE:TEXT/JAVASCRIPT;CHARSET=UTF-8;");
Sleep (2);
?>
Document.body.innerhtml= "Body Content has Been changed";
Using defer it is necessary to note that since the execution time of the defer is after the parsing of the page, the external script execution times containing the defer are given precedence over the inline script, as in the following, a domcontentloaded event listener is placed in the inline script:

<! DOCTYPE html>
<meta charset= "UTF-8" >
<script>
Document.addeventlistener ("domcontentloaded", function () {
Console.log ("Internal script, domcontentloaded happening!");
},false);
</script>>
<script src= "./js.js" defer></script>
<!--external script content: Console.log ("external script, Load complete!"); -->
<body>
This is the Document.
</body>
The external script content is found to be printed first.

For an external script that uses async, it executes immediately after the JavaScript file is fully loaded, so it may be executed before the DOM is loaded, or it may be executed later. The problem here is that if the asynchronous-loaded JS is executed after the DOM is ready, the action of the DOM will not be performed, and if it is executed before the DOM is ready, the domcontentloaded event cannot be monitored. An event callback that relies on domcontentloaded cannot be started. For example, an HTML page adds the following asynchronous scripting code:

<?php
Header ("Content-type:text/javascript");
Sleep (5);
?>
Document.addeventlistener ("Load", function () {
Console.log (' domcontentloaded Event ');
},false);


found that "domcontentloaded event" could not be printed, and after removing the async attribute, the "domcontentloaded event" is printed normally, which means that after an asynchronous load, the external script executes The domcontentloaded incident is over.

In summary, the biggest difference between defer and async is the difference in execution time, defer is done immediately after the DOM parsing, and async is executed immediately after the script is downloaded. The timing of the implementation of the difference between the final results are different, in the actual need to be careful treatment.

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.