Implementation principle of synchronous loading and asynchronous loading of javascript files

Source: Internet
Author: User

Script attributes of HTML 4.01
Charset: Optional. Specifies the character set of the src introduced code. This value is ignored by most browsers.
Defer: boolean, optional. Delayed script execution is equivalent to placing the script tag at the bottom of the page body Tag. The js script will be executed before DOMContentLoaded of the document. Other browsers, except IE and Firefox, are not supported.
Language: discarded. This value is ignored in most browsers.
Src: Optional. Specifies the external code file to be introduced without specifying the suffix.
Type: required. Specifies the content type (MIME type) of the script ). In reality, this value is usually not specified. The browser will interpret and execute it as text/javascript by default.

Script attributes in HTML5:
In addition to the attributes defined by the new HTML5 standard, the script tag removes the language attribute and modifies the type attribute as optional (default text/javascript) compared with HTML4.01 ), and added a property async.
Async: boolean. It defines whether the script is executed asynchronously. The value is true or false.
If async is set to true, the defer attribute is ignored.
The Asynchronous JavaScript file is assumed that no document is used. write () writes content to the loaded document. Therefore, do not use document during the loading and execution of js files that are asynchronously executed. write ()
In addition to the script tag attribute, the loading and execution methods of js files are affected by the introduction of pages:
Any js file introduced by adding a script node (such as appendChild (scriptNode) is executed asynchronously (scriptNode needs to be inserted into the document, only creating nodes and setting src will not load js files, which is incomparable with the pre-loading of img)
The code in the <script> label in the html file or the code in the js file referenced by src is synchronously loaded and executed.
The code in the <script> label in the html file is imported using document. write (). The js file is executed asynchronously.
In the code of the js file referenced by the <script> label src attribute in the html file, the js file imported using the document. write () method is executed synchronously.
Use the Image object to asynchronously pre-load js files (not executed)

Do not initiate a request to load the js file by using the following method:
DivNode. innerHTML = '<script src = "xxx. js"> </script> ';
The window. onload event is triggered after the js file is loaded (even asynchronous loading)
========================================================== ==================
1,
<Script>
// Synchronously load the executed code
</Script>
2,
<Script src = "xx. js"> </script> // synchronously load and execute the code in xx. js.
3,
<Script>
Document. write ('<script src = "xx. js"> <\/script>'); // asynchronously load and execute the code in xx. js.
</Script>
4,
<Script src = "xx. js"> </script>
The following code is available in xx. js:
Copy codeThe Code is as follows:
Document. write ('<script src = "11.js"> <\/script> ');
Document. write ('<script src = "22.js"> <\/script> ');

Then, xx. js, 11.js, and 22.js are both loaded and executed simultaneously.
If xx. js, 11.js, and 22.js are asynchronously loaded by inserting script nodes, 11.js and 22.js are asynchronously loaded,
If xx. js is asynchronously loaded as a script node, and 11.js and 22.js are loaded as document. when the write (script) method is used for loading, 11.js and 22.js are synchronously loaded (tested by the latest browser, in chrome, xx. j. document cannot be used for asynchronous loading and execution. write () writes content to the document, but firefox and IE can be written before the document is closed (by alert in html to prevent the document from being closed ))
Test: at 11. alert () in js (do not use the for loop. The Browser executes the code in a single thread. Continuous execution of any piece of code will cause the rest of the code to be blocked), and console in 22.js. log (), you can see 22. code in js is blocked
5,
In the following method, xx. js asynchronously loads and runs after the appendChild execution.
Copy codeThe Code is as follows:
Var script = document. createElement ("script ");
Script. setAttribute ("src", "xx. js ");
Documenrt. getElementsByTagName ("head") [0]. appendChild (script );

6. Use the Image object to asynchronously pre-load js files (not executed)
When the Image's src value is assigned, a request is initiated, and the file type is not picky (the Image may also be dynamically created by a script, such as a verification code ), therefore, the url of the js file can be assigned to the image. src and js are cached by the browser after being loaded.
Copy codeThe Code is as follows:
Var img = new Image ();
Img. onload = function () {alert (1) ;}; // the onload callback function is not triggered because the returned Javascript file MIME is not an image.
Img. src = 'HTTP: // localhost/test/loadjs/try.2.j ';
Var s = document. createElement ("script ");
Var h = document. getElementsByTagName ("head") [0];
// Execute js
S. src = img. src;
H. appendChild (s );

A function for loading js files:
Copy codeThe Code is 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 tag. There is an onreadystatechange event in IE, And the w3c standard has an onload event.
// These readystates are for IE8 and below. W3C standard script labels do not have onreadystatechange or this. readyState,
// Failed to load the file. onload will not execute,
//(! This. readyState) is designed for W3C standards, and IE 9 also supports W3C standard onload.
If ((! This. readyState) | this. readyState = "complete" | this. readyState = "loaded "){
Callback ();
}
} // End onreadystatechange
}

For testing at (synchronous loading) (insert alert to easily see blocking during loading)
Tryjs.html
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<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>
</Html>

Tryjs. js
Copy codeThe Code is 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 codeThe Code is as follows:
Console. log ('loadjs 1 begin ');
Console. log ('loadjs 1 finished ');

Try.2.js
Copy codeThe Code is as follows:
Console. log ('loadjs 2 begin ');
Console. log ('loadjs 2 finished ');

Test results (the callback complete of file 2 and file 1 is in the order of IE7 \ 8 \ 9)
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.