JavaScript asynchronous loading details (browser loading in JavaScript) _javascript tips

Source: Internet
Author: User
Tags eval script tag
The form of synchronous loading and asynchronous loading
1. Synchronous loading
This is the type of synchronous loading that we usually use most often:
<script src= "Http://yourdomain.com/script.js" ></script>
Synchronous mode, also known as blocking mode, blocks subsequent processing of the browser, stops subsequent parsing, and therefore stops subsequent file loads (such as images), rendering, and code execution.
JS is to be synchronized, because JS may have output document content, modify the DOM, redirection and other behavior, so the 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, but 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)
Copy Code code as follows:

(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:
Copy Code code as follows:

(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
Copy Code code as follows:

(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
Because of the dynamic nature of JavaScript, there are many asynchronous loading methods:
XHR Eval
XHR Injection
Script in Iframe
Script Defer
document.write Script Tag
Another method is to use settimeout delay of 0 seconds with other methods combined.
XHR eval: Get JS content via Ajax, and then Eval execute.
var xhrobj = Getxhrobject ();
Copy Code code as follows:

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.
Copy Code code as follows:

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.
Copy Code code as follows:

<script type= "Text/javascript" >
/*
Var...
*/
</script>

See Resources in the 2010 Velocity conference Steve Souders and Taobao's two handouts.

II, Async and Defer properties

1. Defer properties
<script src= "File.js" defer></script>
The Defer property declares that there will be no document.write or DOM modifications in this script.
The browser will download file.js and other script with defer properties in parallel without blocking subsequent processing of the page.
The defer property is implemented in IE 4.0 for more than 13 years! Firefox supports the defer property starting at 3.5.
Note: All defer scripts are guaranteed to be executed sequentially.
2. Async Properties
<script src= "File.js" async></script>
The Async property is HTML5 added. function is similar to defer, but it will be executed as soon as it is downloaded and cannot guarantee that the script will execute sequentially. They will be completed before the OnLoad event.
Firefox 3.6, Opera 10.5, IE 9, and the latest chrome and Safari all support the async attribute. Async and defer can be used at the same time, so all ie after IE 4 supports asynchronous loading.
3. Explain in detail
<script> tags in HTML 4.01 differ from HTML5:
The type attribute is required in HTML 4 and is optional in HTML5.
The Async property is new in HTML5.
Individual properties (Xml:space) are not supported in HTML5.
Description
Without the Async property, the script will get (download) and execute immediately before continuing with the subsequent processing, which blocks the browser's post-processing.
If there is a async property, the script is downloaded and executed asynchronously, and the browser continues to follow up on the process.
HTML4 has the Defer property, which prompts the browser that the script will not produce any document elements (no document.write), so the browser continues to follow up and render.
If there is no async property but there is a defer property, the script will execute after the page parse.
If both are set, then the Defer property is intended primarily to allow older browsers that do not support the async attribute to be treated in the original defer manner, rather than in a synchronized manner.
See also official note: script Async
Personal supplement:
Since asynchronous loading is already supported in HTML5, why use the same kind of hassle (dynamically creating a SCRIPT element) that was previously recommended?
A: To be compatible, async old browsers are not supported yet. If all browsers are supported in the future, it is easiest to add the async attribute directly to the script.

third, delay loading (lazy loading)

This solves the problem of asynchronous loading (async loading), and then what is deferred loading.
Deferred loading: Some JS code is not immediately required when the page is initialized, and some situations are needed later. Delay loading is the beginning does not load these temporarily unused JS, but in need of time or later through the control of JS to asynchronously load.
That is, the JS cut into a number of modules, the page is initialized to load only need to execute immediately JS, and then other JS load delay to the first time when the need to load.
In particular, the page has a large number of different modules, many may not be temporarily or simply useless to.
Just like the delayed loading of a picture, the picture is loaded when it appears in the viewable area (pulled down in the scroll bar).

Iv. Two-stage loading and delay execution of script (lazy execution)

JS loading is actually composed of two phases: download content (download bytes) and execution (parse and execute).
After downloading the content of JS, the browser will parse and execute it immediately, whether it is synchronously loaded or asynchronously loaded.
The preceding asynchronous load solves only the download phase problem, but the code executes immediately after downloading.
and the browser in the resolution of the JS stage is blocking any operation, the browser is in a unresponsive state.
We all know that it takes time to download the script over the network, but it's easy to ignore the second stage, and parsing and execution takes time. Script parsing and execution took more time than we thought, especially when the script was a lot bigger. Some require immediate execution, while others do not need to (for example, just to show an interface or perform an operation).
These script can be deferred execution, the first asynchronous download cache, but not immediately executed, but at the first time needed to execute once.
Use special techniques to separate downloads from execution (thanks again to the dynamic nature of JavaScript). For example, the content of JS is cached as image or object, so it is not executed immediately and then executed at the first time when needed.
For more explanations in this section, see the related links in Controljs at the end of the reference.
Small tips:
1. Simulate a longer download time:
Write a back-end script to sleep for a certain amount of time. such as in the JSP Thread.Sleep (5000); , so you can receive the content in 5 seconds.
2. Simulate long JS code execution time (because this step is generally faster and less easy to observe):
var t_start = number (new Date ());
while (T_start + 5000 > number (New Date ()) {}
This code will allow JS to perform 5 seconds to complete!

v. History of the use of script tags

1. Script in head
Copy Code code as follows:

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

blocked subsequent downloads;
In IE 6-7 script is downloaded sequentially, rather than the current "parallel download, sequential execution" approach;
Block rendering (rendering) during download and resolution execution phase;
2. Script placed at the bottom of the page (2007)
...
<script src= "..." ></script>
</body>

does not prevent other downloads;
In IE 6-7 script is downloaded sequentially;
Block rendering (rendering) during download and resolution execution phase;
3. Load script asynchronously (2009)
Copy Code code as follows:

var se = document.createelement (' script ');
SE.SRC = ' http://anydomain.com/A.js ';
document.getElementsByTagName (' head ')
[0].appendchild (SE);


This is the way this article mainly says.
does not prevent other downloads;
In all browsers, script is downloaded in parallel;
Block rendering (rendering) only during parse execution phase;
4. Asynchronous download + On-Demand Execution (2010)
Copy Code code as follows:

var se = new Image ();
Se.onload = Registerscript ();
SE.SRC = ' http://anydomain.com/A.js ';

Separating the download JS from the parse execution JS
does not prevent other downloads;
In all browsers, script is downloaded in parallel;
Do not block rendering (rendering) until it is really needed;
The problem of asynchronous loading
You cannot use document.write to output document content while loading asynchronously.
In sync mode, document.write prints the document at the location where the current script is located. In asynchronous mode, the browser continues to process subsequent page content and cannot determine where document.write should be exported, so document.write in asynchronous mode is not possible. When the page is already onload, then executing document.write will cause the contents of the current page to be emptied because it automatically triggers the Document.open method.
In fact, Document.Write's reputation is not good, preferably less.
Alternate Method:
1. Although asynchronous loading cannot be document.write, it is possible to perform the action Dom (creating the DOM or modifying the DOM) after onload so that you can implement some of your own dynamic output. For example, to create a floating element asynchronously on a page, it doesn't matter where it is in the page, just create the DOM element to add to the document.
2. If you need to asynchronously generate the contents of an element in a fixed position, you can set a DOM element as the target in that fixed position, so that you know the location, and you can modify the element after it has been loaded asynchronously.
Six, JS Modular management
Asynchronous loading requires that all JS content be split into a modular way to organize, in which there is a dependency, and asynchronous loading does not guarantee the order of execution.
In addition, namespace how to manage and other related issues. This section is beyond the content of this article and can be referred to:
requirejs ,  CommonJS  and Wang Paoping (Taobao)  SeaJS  and its blogs  .
Seven, JS best practices:
1. Minimize the JS file, minimize it with the compression tool, and turn on HTTP gzip compression. Tools:
2. Try not to put in 3. Avoid using the Document.Write method
4. Asynchronously loading JS, using non-blocking side , is the content of this article.
5. Try not to use Inline Javascript directly on page elements, such as onclick. Facilitates unified maintenance and caching processing.
Resources:
Lazy Loading asyncronous Javascript
Load Non-blo cking JavaScript with HTML5 Async and Defer
2010 Velocity two handouts:
Steve Souders (Google)  Even Faster Web Sites  (pdf)
Li Mu (Taobao) &nbs p; third-party AD code stability and performance Optimization combat   (PDF)
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.