Three ways to load JS asynchronously

Source: Internet
Author: User
Tags script tag

One, synchronous loading

One of the most common ways we usually use.

<src= "Http://yourdomain.com/script.js"></script  ><src= "Http://yourdomain.com/script.js"></ Script >

Synchronous mode, also known as blocking mode, will prevent the subsequent processing of the browser, stop subsequent parsing, and only if the current load is complete, the next step can be done. So the default synchronous execution is safe. However, if JS in the output document content, modify DOM, redirect and other behavior, will cause the page blocked. Therefore, it is generally recommended to put <script> tags at <body> end, so as to minimize page blocking.

Second, asynchronous loading

Asynchronous loading is also called non-blocking loading, and the browser will continue to process the subsequent pages while downloading and executing JS. There are three main ways of doing this.

Method One: Also called the script DOM Element
1 (function () {2     var scriptele = document.createelement ("script"), 3     scriptele.type = "Text/javasctipt"; 4     Scriptele.async = true;5     scriptele.src = "Http://cdn.bootcss.com/jquery/3.0.0-beta1/jquery.min.js"; 6     var x = document.getElementsByTagName ("Head") [0];7     X.insertbefore (Scriptele, x.firstchild);        8  }) ();

The <async> property is a new asynchronous support in HTML5 . This method is called the script DOM Element method. This asynchronous loading code is used by both Google Analytics and the Badge Google +

1 (function () {; 2     var ga = document.createelement (' script '); 3     ga.type = ' Text/javascript '; 4     Ga.async = True ; 5     ga.src = (' https: ' = = Document.location.protocol? ' Https://ssl ': ' http://www ') + '. Google-analytics.com/ga.js '; 6     var s = document.getelementsbytagname (' script ') [0]; 7     S.parentnode.insertbefore (GA, s); 8});

However, this loading method prevents the OnLoad event from triggering until it is executed, and now many of the page's code is performing additional rendering work at OnLoad, so it still blocks the initialization of some pages.

Method Two: Asynchronous loading at onload
1 (function () {2     if (window.attachevent) {3         window.attachevent ("Load", asyncload); 4     }else{5         Window.addeventlistener ("Load", asyncload); 6     } 7     var asyncload = function () {8         var ga = document.createelement (' script ');  9         ga.type = ' text/javascript ';         Ga.async = true;         ga.src = (' https: ' = = Document.location.protocol? ' Https://ssl ': ' http://www ') + '. Google-analytics.com/ga.js ';         var s = document.getelementsbytagname (' script ') [0];         s.parentnode.insertbefore (GA, s);     }15) () ;

This method simply puts the script insertion method inside a function and then executes it in the OnLoad method of window, which solves the problem of blocking onload event triggering.

Note: The difference between domcontentloaded and load. The former is in the document has been resolved to complete, the page of DOM elements available, but the page image, video, audio and other resources are not loaded, function with the Ready event in jquery, the latter difference is that the page all the resources are loaded.

Method Three: Other methods

Due to the dynamic nature of JavaScript, there are many asynchronous loading methods: XHR injection, XHR Eval, script in Iframe, script defer attribute, document.write (script tag).

XHR Injection (XHR injection): Use XMLHttpRequest to get JavaScript, and then create a SCRIPT element to insert into the DOM structure. After the AJAX request succeeds, set Script.text to the ResponseText returned after the request succeeds.

1  //Get XMLHttpRequest object, consider compatibility. 2     var getxmlhttp = function () {3         var obj; 4         if (window). XMLHttpRequest) 5             obj = new XMLHttpRequest (); 6         Else 7             obj = new ActiveXObject ("Microsoft.XMLHTTP"); 8         return obj; 9     };     x//HTTP request get mode; The third parameter of the open () method indicates whether to handle one     var xmlHttp = Getxmlhttp () with asynchronous (true) or synchronous (false);     Xmlhttp.open ("GET", "Http://cdn.bootcss.com/jquery/3.0.0-beta1/jquery.min.js", true);     Xmlhttp.send (); 14     Xmlhttp.onreadystatechange = function () {         Xmlhttp.readystate = = 4 && xmlhttp.status = = 200) {16< C17/>var script = document.createelement ("script");             script.text = xmlhttp.responsetext;18             document.getElementsByTagName ("Head") [0].appendchild (script);         }20            

XHR Eval: Unlike the XHR injection for ResponseText, the responsetext is placed directly inside the eval () function.

1  //Get XMLHttpRequest object, consider compatibility. 2     var getxmlhttp = function () {3         var obj; 4         if (window). XMLHttpRequest) 5             obj = new XMLHttpRequest (); 6         Else 7             obj = new ActiveXObject ("Microsoft.XMLHTTP"); 8         return obj; 9     };     x//HTTP request get mode; The third parameter of the open () method indicates whether to handle one     var xmlHttp = Getxmlhttp () with asynchronous (true) or synchronous (false);     Xmlhttp.open ("GET", "Http://cdn.bootcss.com/jquery/3.0.0-beta1/jquery.min.js", true);     Xmlhttp.send (); 14     Xmlhttp.onreadystatechange = function () {         Xmlhttp.readystate = = 4 && xmlhttp.status = = 200) {16< C17/>eval (Xmlhttp.responsetext);             //alert ($);//can pop up $, indicating that JS has been loaded in. The Click event puts a problem in the other, which should not have been loaded in             the $ ("#btn1"). Click (function () {                 alert (this). text ());             21});         }22     }        

Script in Irame: Inserts an IFRAME element in the parent window and then performs the load JS operation in the IFRAME.

1 var Insertjs = function () {alert (2)};2 var iframe = document.createelement ("iframe"); 3 Document.body.appendChild (iframe); 4 var doc = iframe.contentwindow.document;//Gets the window in the IFRAME to use the Contentwindow property. 5 Doc.open (); 6 Doc.write ("<script>varInsertjs= function(){};<\/script><body onload= ' Insertjs () ' ></Body>");7doc.close ();

GMail Mobile: The industry JS content is commented, so will not be executed, when needed, get the text content in the script to remove comments, call eval () execution.

1 <script type= "Text/javascript" > 2/     *    4     * /5     </script>
HTML5 New properties: Async and Defer properties

Defer property: IE4.0 appears. There will be no document.write and DOM modifications in the defer declaration script. The browser will download other script with the defer attribute in parallel. It does not block subsequent processing of the page. Note: All defer scripts must be guaranteed to be executed sequentially.

<script type= "Text/javascript" defer></script>

Async properties are supported in Firefox 3.6, Opera 10.5, IE 9, and the latest Chrome and Safari. You can use both async and defer, so that all IE after IE 4 supports asynchronous loading.

Without the async attribute, script will get (download) and execute immediately, blocking the browser's subsequent processing. If there is an async attribute, the script is downloaded and executed asynchronously, while the browser continues with subsequent processing.

Third, delay loading

Some JS code in some cases need to use, not when the page is initialized to use. Lazy loading is to solve this problem. JS cut into a number of modules, the page is initialized to load only the JS that need to be executed immediately, and then other JS loading delay until the first time needed to load again. Lazy loading of similar images.

JS loading is divided into two parts: Download and execute. Asynchronous loading only solves the problem of downloading, but the code executes immediately after the download is complete, and the browser is blocked during execution and cannot respond to any requirements.

Solution: In order to solve the problem of JS delay loading, it can be cached by using asynchronous loading, but not immediately, when needed to execute. How do I cache it? The JS content is cached as an image or object, so it is not executed immediately and is executed at the first need.

  

  1: Simulate a longer download time:

Use thread to let it sleep for a while to perform the download operation.

2: Simulate longer JS code execution time    

    var start = number (new Date ());

while (start + > number (new Date ())) {//Execute JS}

    This code will make JS execution 5 seconds to complete!


JS lazy loading mechanism (lazyload): Simply put, it is in the browser to scroll to a location in the trigger related functions, to implement the loading of page elements or the execution of certain actions. How to implement the browser scrolling position detection? Can be implemented by a timer to determine if a function needs to be executed by comparing the location of the page target node and the height of the browser scroll bar at a certain time.

Three ways to load JS asynchronously

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.