The principle _javascript technique of synchronous loading and asynchronous loading of JavaScript files

Source: Internet
Author: User
Tags script tag
script properties for HTML 4.01
CharSet: Optional. Specifies the character set in which SRC introduces code, and most browsers ignore the value.
Defer:boolean, optional. Delaying script execution is equivalent to putting the script tag at the bottom of the page body tag, and the JS script executes before the document Domcontentloaded. In addition to IE and newer versions of Firefox, other browsers are not supported.
Language: Obsolete. This value is ignored by most browsers.
SRC: Optional. Specifies the imported external code file, without limiting the suffix name.
Type: Must be selected. Specifies the content type (MIME type) of the script. This value is usually not specified in reality, and the browser defaults to the Text/javascript type to interpret execution.

the Script property in HTML5
In addition to the properties defined by HTML5 New standard, the script tag removes the language attribute from the HTML4.01 compared to the HTML5, modifies the Type property to optional (default text/javascript), and adds a new property async.
Async:boolean, the function of a property that defines whether a script executes asynchronously, evaluates to TRUE or FALSE.
If Async is set to true, the defer property is ignored.
The JS file that executes asynchronously is assumed to write content to document in load without using document.write (), so do not use document.write () in the execution of the asynchronous JS file loading.
In addition to the script tag properties, the way the page introduces the JS file affects how it is loaded:
Any JS file introduced in a way that adds a script node (such as AppendChild (Scriptnode)) is executed asynchronously (Scriptnode needs to be inserted into the document, creating only nodes and setting SRC is not going to load the JS file, which follows the IMG Preload cannot be analogous)
The code in the <script> tag in the HTML file or in the JS file referenced by SRC is synchronously loaded and executed
The code in the <script> tag in the HTML file uses the document.write () method to introduce the JS file to be executed asynchronously
HTML file <script> tag src attribute referenced in the code of the JS file using the document.write () method to introduce the JS file is synchronously executed
Pre-loading JS files asynchronously using the Image object (not executed)

Do not use the following procedure, which does not initiate a request to load a JS file:
divnode.innerhtml = ' <script src= ' xxx.js ' ></script> ';
The Window.onload event will not be triggered until the JS file is loaded (even if it is loaded asynchronously)
=====================================================
1,
<script>
To load executed code synchronously
</script>
2,
<script src= "Xx.js" ></script>//synchronous loading of code in execution xx.js
3,
<script>
document.write (' <script src= ' xx.js "><\/script>"); To load code in execution Xx.js asynchronously
</script>
4,
<script src= "Xx.js" ></script>
Xx.js has the following code:
Copy Code code as follows:

document.write (' <script src= ' 11.js ' ><\/script> ');
document.write (' <script src= ' 22.js ' ><\/script> ');

Then the Xx.js and 11.js, 22.js are both loaded and executed synchronously.
If Xx.js, 11.js, and 22.js are loaded asynchronously by inserting the script node, 11.js and 22.js are loaded asynchronously.
If the xx.js is loaded asynchronously as a script node, 11.js and 22.js are loaded in document.write (script) mode, 11.js and 22.js are loaded synchronously (with the latest browser testing, under Chrome, XX.J asynchronous Load execution has been unable to write content to the document using document.write (), but Firefox and IE can be written before document closes (by alert in HTML to prevent the document from closing)
Test: In 11.js alert () (Do not use for loop, browser is single-threaded execution, continuous execution of any piece of code will cause the rest of the code is blocked), 22.js console.log (), you can see the code in 22.js is blocked
5,
In this way, xx.js will load execution asynchronously after AppendChild executes
Copy Code code as follows:

var script = document.createelement ("script");
Script.setattribute ("src", "xx.js");
Documenrt.getelementsbytagname ("Head") [0].appendchild (script);

6. Use Image object to preload JS file asynchronously (will not be executed)
When the src of image is assigned, the request is made, and the file type is not picky (the picture may be created dynamically, such as the verification Code), so the URL of the JS file can be assigned to IMAGE.SRC, and JS is cached by the browser after loading.
Copy Code code as follows:

var img = new Image ();
Img.onload = function () {alert (1);}; The onload callback function is not triggered because the returned JS file MIME is not a picture
IMG.SRC = ' http://localhost/test/loadjs/try.2.js ';
var s = document.createelement ("script");
var h = document.getelementsbytagname ("head") [0];
Execute JS
S.SRC=IMG.SRC;
H.appendchild (s);

A function to load a JS file:
Copy Code code as follows:

var Loadjs = function (url,callback) {
var head = document.getElementsByTagName (' head ');
if (head&&head.length) {
head = head[0];
}else{
head = document.body;
}
var script = document.createelement (' script ');
script.src = URL;
Script.type = "Text/javascript";
Head.appendchild (script);
Script.onload = Script.onreadystatechange = function () {
Script tags, IE under the onReadyStateChange event, the standard for the OnLoad event
These readyState are for IE8 and below, and the standard script tags for the consortium are not onreadystatechange and this.readystate,
File load not successful onload will not execute,
(!this.readystate) is for the standard of the consortium, IE 9 also supports the standard onload
if ((!this.readystate) | | this.readystate = = "complete" | | | this.readystate = = "Loaded") {
Callback ();
}
}//end onreadystatechange
}

For the 4th Test (synchronous loading) (where alert is inserted it is easy to see blocking at load time)
Tryjs.html
Copy Code code as follows:

<! DOCTYPE html>
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<script src= "Tryjs.js"
Onload= "if (!document.all) {console.log (' outer JS callback, not IE ');}"
Onreadystatechange= "Console.log (' outer JS callback ', This.readystate, ' IE ');" ></script>
<body>
</body>

Tryjs.js
Copy Code code as follows:

Console.log (' write begin ');
document.write (' <script src= "try.1.js" onreadystatechange= "Console.log (\ ' file 1 callback \ ', this.readystate,\ ' IE \ '); "onload=" if (!document.all) {console.log (\ ' file 1 callback,not IE \ ');} " ><\/script> ');
document.write (' <script src= "try.2.js" onreadystatechange= "Console.log (\ ' file 2 callback \ ', this.readystate,\ ' IE \ '); "onload=" if (!document.all) {console.log (\ ' file 2 callback,not IE \ ');} " ><\/script> ');
Console.log (' write finished ');

Try.1.js
Copy Code code as follows:

Console.log (' Loadjs 1 begin ');
Console.log (' Loadjs 1 finished ');

Try.2.js
Copy Code code as follows:

Console.log (' Loadjs 2 begin ');
Console.log (' Loadjs 2 finished ');

Test results (callback complete of file 2 and file 1 are indeterminate in ie7\8\9 order)
IE 7:
LOG: Outer JS callback loading IE
LOG: Outer JS callback loaded IE
LOG: Write begin
LOG: Write finished
LOG: Outer JS callback Complete IE
LOG: File 1 callback loading IE
LOG: File 2 callback loading IE
LOG: Loadjs 1 begin
LOG: Loadjs 1 finished
LOG: Loadjs 2 begin
LOG: Loadjs 2 finished
LOG: File 2 callback Complete IE
LOG: File 1 callback complete IE

IE8:
LOG: Outer JS callback loading IE
LOG: Outer JS callback loaded IE
LOG: Write begin
LOG: Write finished
LOG: Outer JS callback Complete IE
LOG: File 1 callback loading IE
LOG: File 2 callback loading IE
LOG: Loadjs 1 begin
LOG: Loadjs 1 finished
LOG: Loadjs 2 begin
LOG: Loadjs 2 finished
LOG: File 2 callback Complete IE
LOG: File 1 callback complete IE

IE9:
LOG: Write begin
LOG: Write finished
LOG: Outer JS callback Complete IE
LOG: File 1 callback loading IE
LOG: File 2 callback loading IE
LOG: Loadjs 1 begin
LOG: Loadjs 1 finished
LOG: Loadjs 2 begin
LOG: Loadjs 2 finished
LOG: File 1 callback complete IE
LOG: File 2 callback Complete IE

FIREFOX:
Write begin
Write finished
Outer JS callback, not IE
Loadjs 1 begin
Loadjs 1 finished
File 1 Callback,not IE
Loadjs 2 begin
Loadjs 2 finished
File 2 Callback,not IE

Chrome:
Write begin
Write finished
Outer JS callback, not IE
Loadjs 1 begin
Loadjs 1 finished
File 1 Callback,not IE
Loadjs 2 begin
Loadjs 2 finished
File 2 Callback,not IE
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.