The async attribute of the script loads the script in non-blocking mode.

Source: Internet
Author: User

1. HTML5 implements the async attribute of the scriptThis new attribute allows js to be loaded in non-blocking mode in the browser. In addition, the script also has a defer attribute, all browsers have implemented this attribute (except earlier versions of firefox and chrome). IE has done a good job in this aspect and has supported some attributes from the very beginning.
Copy codeThe Code is as follows:
// Async
<Script async src = "dquery. js" async> </script>

// Defer
<Script async src = "dquery. js" defer>
</Script>

2. Differences between async and defer:
Scripts with async or defer will be immediately downloaded and will not block page parsing, and an optional onload event will be provided for processing, which will be called after the script is downloaded, used for initialization related to this script. The difference is that async is executed immediately once the download is complete (in the window. before the onload event), do not ensure the execution order, and defer can ensure that js is executed in the order of its in the page (before the DOMContentLoaded event ).
3. Use the following code to solve browser compatibility problems
Copy codeThe Code is as follows:
Function lazyload (){
Var elem = document. createElement ("script ");
Elem. type = "text/javascript ";
Elem. async = true;
Elem. src = "js/dquery. js? V = 11 "; // corresponding JS File
Document. body. appendChild (elem );
}

If (window. addEventListener ){
Window. addEventListener ("load", lazyload, false );
} Else if (window. attachEvent ){
Window. attachEvent ("onload", lazyload );
} Else {
Window. onload = lazyload ;}

Because it is asynchronously loaded, you need to use the corresponding js content in the window. onload event. A script error will be reported directly on the page, for example:

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.