Javascript/jquery Asynchronous Load Usage method (1/2)

Source: Internet
Author: User
Tags eval script tag

First, synchronous loading and asynchronous loading form
1. Synchronous loading
This is the type of synchronization loading that we usually use most often:
<script src= "Http://yourdomain.com/script.js" >< /script> synchronous mode, also known as blocking mode, prevents subsequent processing of the browser and stops subsequent parsing, thus stopping subsequent file loads (such as images), rendering, and code execution.
 js to execute synchronously because JS may have output document content, modify DOM, redirect, and so on, so default synchronous execution is safe.
The previous general recommendation is to put <script> at the end of the page </body> before, so as to minimize this blocking behavior, and first let the page display.
Simply put: The load of the network timeline is a waterfall model, while the asynchronous loading of the timeline is the concurrency model.
2. Common asynchronous Loading (Script DOM Element)

The code is as follows Copy Code
(function () {
var s = document.createelement (' script ');
S.type = ' Text/javascript ';
S.async = true;
S.SRC = ' http://yourdomain.com/script.js ';
var x = document.getelementsbytagname (' script ') [0];
X.parentnode.insertbefore (S, x);
})();

Asynchronous loading is also called non-blocking, the browser in the download to execute JS also will continue to follow the page processing.


This approach is to create a SCRIPT element and insert it into the document in the <script> tab of the page, using JS. This is done with non-blocking download JS code.
The Async property is a new asynchronous support in HTML5, as explained in the following article, plus good (no effect).
This method is called the Script DOM Element method and does not require JS homology.
The way to wrap the JS code in an anonymous function and execute it immediately is to protect the variable name from being exposed externally, which is a common way, especially in the JS library.
For example, Google Analytics and + + Badge Use this asynchronous loading code:

The code is as follows Copy Code
(function () {
var ga = document.createelement (' script '); 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);
}) ();(function ()
{var po = document.createelement ("script");
Po.type = "Text/javascript"; Po.async = TRUE;PO.SRC = "Https://apis.google.com/js/plusone.js";
var s = document.getelementsbytagname ("script") [0];
S.parentnode.insertbefore (PO, s);
})();

However, this loading method prevents the OnLoad event from triggering until the load is executed, and now many page codes have to perform additional rendering work in the onload, so it still blocks the initialization of some pages.


3. OnLoad Asynchronous loading

The code is as follows Copy Code
(function () {
function Async_load () {
var s = document.createelement (' script ');
S.type = ' Text/javascript ';
S.async = true;
S.SRC = ' http://yourdomain.com/script.js ';
var x = document.getelementsbytagname (' script ') [0];
X.parentnode.insertbefore (S, x);
}
if (window.attachevent)
Window.attachevent (' onload ', async_load);
Else
Window.addeventlistener (' Load ', async_load, false);
})();

This is similar to the previous approach, but the key is that it does not begin asynchronously loading JS immediately, but only when the onload begins to load asynchronously. This solves the problem of blocking onload event triggering.
Added: domcontentloaded and OnLoad events
Domcontentloaded: page (document) has been parsed, and the DOM elements in the page are already available. However, the pictures and subframe that are referenced in the page may not have finished loading.
OnLoad: All resources on the page are loaded (including pictures). The browser's load schedule stops at this point.
These two time points are divided into three stages of the timeline of the page loading.
4. Other methods of asynchronous loading

Due to the dynamic nature of JavaScript, there are also many asynchronous load methods:
1.XHR Eval
2.XHR injection
3.Script in Iframe
4.Script Defer
5. document.write Script Tag
6. Another method is to use settimeout to delay 0 seconds with other methods.
XHR eval: Get JS content via Ajax, and then Eval execute.

  code is as follows copy code
var xhrobj = Getxhrobject ();
 xhrobj.onreadystatechange =
   function () {
     if ( Xhrobj.readystate!= 4) return;
     eval (xhrobj.responsetext);
  };
 xhrobj.open (' Get ', ' a.js ', true);
 xhrobj.send ("); Script in Iframe: Creates and inserts an IFRAME element so that it executes JS asynchronously.
var iframe = document.createelement (' iframe ');
 document.body.appendchild (IFRAME);
 var doc = iframe.contentWindow.document;
 doc.open (). Write (' <body onload= ' Insertjs () ">");

Doc.close (); GMail Mobile: Page JS content is commented, so will not execute, and then when needed, get the script element text content, remove the comment after eval execution.

The code is as follows Copy Code
<script type= "Text/javascript" >
/*
Var...
*/
</script>

Home 1 2 last page
Related Article

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.