Have to say that JavaScript asynchronous loading

Source: Internet
Author: User
Tags script tag

Problems with synchronous loading

The default JS is synchronous loading, where the "load" can be interpreted as parsing, execution, rather than "download", in the latest version of the browser, the browser for code requests for resources are waterfall-loaded, rather than blocking, but JS execution is always blocked. What is the problem? If my index page to load some JS, but one of the requests is not responding, so block the subsequent JS code execution (synchronous loading), and page rendering can not continue (if JS is introduced in the head tag).

<script type= "Text/javascript" src= ' http://china-addthis.googlecode.com/svn/trunk/addthis.js ' ></script ><script type= "Text/javascript" src= ' http://libs.baidu.com/jquery/2.0.0/jquery.min.js ' ></script>  This is a test

For example, the above code, saved as a index.html file, the main body of the page is a simple string, but the code after the execution of the page is blank, why? Because the requested JS delay loading (may be due to Google Wall and so on), so blocking the execution of the code behind, the page can not be rendered. Perhaps you would suggest, put the JS code before </body> can not be able to render the page first! Good way, we try to put JS in the back:

 This Is a test<script type= "text/javascript" src= ' http://china-addthis.googlecode.com/svn/trunk/addthis.js ' ></script><script type= "Text/javascript" src= ' http://libs.baidu.com/jquery/2.0.0/jquery.min.js ' > </script>

The page was instantly rendered, and the "This is a Test" appeared in the foreground soon, and the world seemed to be calm, but:

 This Is a test<script type= "text/javascript" src= ' http://china-addthis.googlecode.com/svn/trunk/addthis.js ' ></script><script type= "Text/javascript" src= ' http://libs.baidu.com/jquery/2.0.0/jquery.min.js ' > </script><script type= "Text/javascript" >  console.log (' Hello World '); </script>

In the previous code based on a simple add a piece of code, but "Hello World" delay in the console output, obviously the previous JS request blocking the loading of the following code, we suddenly realize that the change of JS loading location can only change the rendering of the page, however, for JS loading and no egg use, JS will still block.

Implementation of JS asynchronous loading

Our requirements seem to be very simple, can be loaded in the page at the same time, the console output string, and then the popular point, is in the request for the first Google provided JS, while continuing to execute the following JS, that is, to achieve the asynchronous loading JS.

The most common practice is to dynamically generate a script tag:

<body> This is    a test  <script type= "Text/javascript" >    ~function () {      var s = document.createelement (' script ');       = ' Http://china-addthis.googlecode.com/svn/trunk/addthis.js ';      Document.body.appendChild (s);    } ();   </script>  <script type= "text/javascript" src= ' http://libs.baidu.com/jquery/2.0.0/jquery.min.js ' ></script>  <script type= "Text/javascript" >    console.log (' Hello World ');  </script></body>

However, there is still a problem, this loading method will block the OnLoad event before the load execution, and now many pages of code in the onload to perform additional rendering work, and so on, it will still block the initialization of some pages of processing:

<body> ThisIs a test<script type= "Text/javascript" > ~function() {      //function Async_load () {        vars = document.createelement (' script '); S.SRC= ' Http://china-addthis.googlecode.com/svn/trunk/addthis.js ';      Document.body.appendChild (s); // }      //window.addeventlistener (' Load ', async_load, false);    }(); Window.onload=function() {      vartxt = document.createtextnode (' Hello World '); Document.body.appendChild (TXT);    }; </script> <script type= "text/javascript" src= ' http://libs.baidu.com/jquery/2.0.0/jquery.min.js ' ></ Script></body>

For example, the above code does not render "Hello World" very well, we just need to remove the comment, so that Google provides JS in the onload only start asynchronous loading. This solves the problem of blocking the onload event triggering.

Supplemental domcontentloaded with OnLoad event domcontentloaded: the page (document) has been parsed and the DOM elements in the page are already available. However, the pictures and subframe referenced in the page may not have been loaded yet. OnLoad: All the resources on the page have been loaded (including pictures). The browser's onboarding progress is not stopped at this point. These two time points timeline the page load into three phases.

The above seems to be a better solution to this problem, but HTML5 provides a simpler way to do this, the async attribute!

 This Is a test<script type= "text/javascript" src= ' http://china-addthis.googlecode.com/svn/trunk/addthis.js ' async= ' async ' ></script><script type= "text/javascript" src= ' http://libs.baidu.com/jquery/2.0.0/ Jquery.min.js ' ></script><script type= "Text/javascript" >  console.log (' Hello World ' ); </script>

Async is a new property of HTML5, and the async attribute specifies that once the script is available, it will execute asynchronously (once the download is complete).

It is important to note that the Async attribute applies only to external scripts (when using the SRC attribute)

The defer property is often mentioned with async:

 This Is a test<script type= "text/javascript" src= ' http://china-addthis.googlecode.com/svn/trunk/addthis.js ' Defer= ' defer ' ></script><script type= "text/javascript" src= ' http://libs.baidu.com/jquery/2.0.0/ Jquery.min.js ' ></script><script type= "Text/javascript" >  console.log (' Hello World ' ); </script>

It seems to achieve the same effect, but is it really the same? Let's take a look at the definition of the defer property.

The previous defer only supported IE's hack, now HTML5 's appearance began to fully support defer. The Defer property specifies that the script will not execute until the page has finished loading. The Defer property applies only to external scripts (only when using the SRC attribute). Ps:ie support defer does not seem to be the case, because there is no sense of IE, do not delve into, interested in the information can be consulted.

Since async and defer often appear together, then discriminate it!

Without the async and defer attributes (assigned to True, the same as below), the browser immediately executes the current JS script, blocking the subsequent script, and if there is an async attribute, the process of loading and rendering subsequent document elements will be parallel to the current JS loading and execution (async) If there is a defer attribute, then the process of loading subsequent document elements will be performed in parallel (asynchronously) with the script.js load, but the execution of the script.js is done before the domcontentloaded event fires after all element (DOM) parsing is complete.

Take a look at a picture of online theft:

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

This diagram tells us the following points (from the difference between defer and async):

    1. defer and async in the network read (download) This piece is the same, is asynchronous (compared to HTML parsing)
    2. The difference between the two is that when the script finishes downloading, it's clear that defer is closest to our request for application script loading and execution.
    3. With regard to defer, the picture is that the script is executed in the order of loading, which is a good use of
    4. Async is a random execution of the main, anyway, for it to load and execute the script is next to each other, so no matter what the order of your declaration, as long as it is loaded, it will be executed immediately
    5. To think about it,async is not very useful for application scripting because it does not consider dependencies at all (even the lowest order), but it is a good fit for those scripts that can be independent of any script or that are not dependent on any script, the most typical example: Google Analytics

  

But it seems to me (the following individuals understand that if there is a discrepancy), the application of defer on asynchronous loading will not be wider than that of async. Async's English explanation is asynchronous, which acts on the script, which causes the script to execute as soon as it is loaded (downloaded), similar to the dynamic insertion of the script tag (async only supports H5, which is compatible with the browser), and defer's English explanation is a delay, and the effect is similar to the literal interpretation, Delaying the execution of the script so that the DOM element is loaded before it begins to execute the script in an orderly fashion, which brings another problem:

 This Is a test<script type= "text/javascript" src= ' http://china-addthis.googlecode.com/svn/trunk/addthis.js ' Defer= ' defer ' ></script><script type= "text/javascript" src= ' http://libs.baidu.com/jquery/2.0.0/ Jquery.min.js ' defer= ' defer ' ></script><script type= ' text/javascript ' src= ' index.js ' defer= ' defer ' > </script>
Console.log (' Hello World ');

If you execute this code, the console's "Hello World" will be slow to get results. So I think it is still async good, if you want to consider dependencies, you can choose Requirejs, Seajs and other module loader.

Summarize

There are several ways in which JavaScript can be loaded asynchronously, such as Ajax eval (using Ajax to get the script content and then using eval (xmlhttp.responsetext) to run the script), the IFRAME mode, and so on.

The above understanding if discrepancies, also hope to point out ~

  

Have to say that JavaScript asynchronous loading

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.