A summary of the differences between defer and async in JavaScript _javascript techniques

Source: Internet
Author: User
Tags script tag blank page

First of all, take a look at these three words:

<script src= "Script.js" ></script>

Without defer or async, the browser will immediately load and execute the specified script, "immediate" means before the document element that is rendered under the script tag, that is, not waiting for subsequent loading of the document element, is read to load and execute.

<script Async src= "Script.js" ></script>

With async, the process of loading and rendering subsequent document elements will be performed in parallel (asynchronous) with script.js loading and execution.

<script defer src= "Myscript.js" ></script>

With defer, the process of loading subsequent document elements will be performed in parallel (asynchronous) with the script.js load, but script.js execution will be completed before the Domcontentloaded event is triggered after all the element parsing is complete.

Here is a detailed introduction to the difference between the two.

General situation

By convention, all script elements should be placed in the head element of the page. The purpose of this approach is to put all references to external files (CSS files and JavaScript files) in the same place . However, including all JavaScript files in the head element of a document means that you must wait until all JavaScript code has been downloaded, parsed, and executed before you can begin rendering the content of the page (the browser begins to render content when it encounters the body tag).

For pages that require a lot of JavaScript code, this will undoubtedly cause the browser to render the page with a noticeable delay, while the browser window in the delay period is blank. To avoid this problem, Web applications are now generally all JavaScript references placed behind the contents of the page in the BODY element. This way, the content of the page is fully rendered in the browser before parsing the included JavaScript code. Users will also feel the speed of opening the page because the browser window shows a shorter time for a blank page.

<! DOCTYPE html>
 
 

Defer (deferred script)

Delay script: The Defer property applies only to external script files.

If you define the defer property for the script tag, the effect of this property is to indicate that the script does not affect the construction of the page when it executes. That is, the script is deferred until the entire page is parsed and then run. Therefore, if the defer property is set in the script element, it is tantamount to telling the browser to download it immediately, but delaying execution.

Example:

<! DOCTYPE html>
 
 

In this example, while we put the script element in the head element of the document, the script contained in it will be deferred until the browser encounters the .
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 preceded by the DOMContentLoaded event (triggered when the DOM tree is built and does not need to wait until all the resources have been loaded) to execute.

Special note: In reality, delay scripts do not necessarily execute sequentially, or they do not occur before the Domcontentloaded event is triggered, so it is best to include only a delay script.

With defer, the process of loading subsequent document elements is performed in parallel (asynchronous) with the script.js load, but script.js execution is completed before the event is triggered after all the element parsing is complete DOMContentLoaded .

Best practices

From a practical standpoint, it's best practice to put all scripts before </body>, because this is the only optimization option for older browsers, and this method guarantees that all other elements of the script are loaded and parsed as quickly as possible.

* * Note: The **defer property does not behave consistently across browsers. To avoid cross browser differences, you can use the "lazy loading" method, which is not loaded until you use the script.

function Lazyload () {
 var elem = document.createelement ("script");
 Elem.type = "Text/javascript";
 Elem.async = true;
 ELEM.SRC = "Script.js"; 
 Document.body.appendChild (Elem);
}

if (window.addeventlistener) {
 window.addeventlistener ("Load", Lazyload, False);
} else if ( window.attachevent) {
 window.attachevent ("onload", lazyload);
} else {
 window.onload = lazyload;
}

Async (Asynchronous script)

Asynchronous script: The Async property also applies only to external script files and tells the browser to download the files immediately.

Unlike defer, however, scripts marked as async do not warrant execution in the order in which they are specified.

<! DOCTYPE html>
 
 

In this example, test2.js may be executed before test1.js. Therefore, it is important to ensure that the two are not mutually exclusive. The purpose of specifying the Async 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. Therefore, it is recommended that asynchronous scripts do not modify the DOM during loading.

Look at a clearer picture:

diagram: Blue Line for network read, red line for execution time, both for script; Green Line for HTML parsing.

Through the above diagram and previous analysis, we can conclude that:

1, defer and async in the network read (script download) This piece is the same, are asynchronous (compared to HTML parsing)

2, the difference between the two: when the script is downloaded after the execution, obviously defer is closest to our application script loading and execution requirements. Defer is immediately downloaded but deferred, and the process of loading subsequent document elements is performed in parallel (asynchronous) with the script's load, but the execution of the script completes before the event is triggered after all the element parsing is complete DOMContentLoaded . Async is immediately downloaded and executed, loading and rendering subsequent document elements in parallel with the loading and execution of the JS script (asynchronous).

3, about defer, we also want to remember is that it is in the order of loading to execute the script

4. Scripts marked as Async are not guaranteed to be executed in the order in which they are specified. For it the script is loaded and executed tightly next to each other, so regardless of the order you declare, it executes immediately as soon as it is loaded.

5. Async is not useful for application scripts because it does not consider dependencies at all (even in the lowest order), but it is appropriate for scripts that can be independent of any script or are not dependent on any script.

Summarize

The above is about JS defer and async the whole content of the difference, the article introduces very detailed, hope to everyone's study or work to bring certain help, if there is doubt 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.