Synchronous loading and asynchronous loading of Javascript files

Source: Internet
Author: User
Tags script tag browser cache

Script property 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 placing the script tag at the bottom of the body tag of the page, and the JS script executes before the document's domcontentloaded. Other browsers are not supported except IE and newer versions of Firefox.
Language: Deprecated. Most browsers will ignore this value.
SRC: Optional. Specifies the imported external code file, without restricting the suffix name.
Type: Required. Specifies the content type of the script (MIME type). In reality, this value is usually not specified, and the browser interprets execution by default as the Text/javascript type.

The Script property in HTML5:

The script tag in HTML5, in addition to the properties defined by the new standard HTML5, removes the language attribute compared to HTML4.01, modifies the Type property to be optional (default text/javascript), and adds a new property, Async.

Async:boolean, the function of the property, defines whether the script executes asynchronously, evaluates to TRUE or FALSE.

If Async is set to true, the defer property is ignored.

The asynchronous execution of the JS file is assumed to not use document.write () to write to the document in the load, so do not use document.write () during the execution of the asynchronous JS file loading

In addition to the script tag properties, the way the page introduces a JS file affects how it is loaded:

    • Any JS file introduced with the addition of a script node (for example, AppendChild (Scriptnode)) is executed asynchronously (thescriptnode needs to be inserted into the document, only the nodes are created and the settings src is not loaded with the JS file (IE 6-9), this is not analogous to the pre-loading of IMG, no special setting Script.type, if set, need to be set to JavaScript type, otherwise will not load JS file (Text/javascript, or with version number, if there is a special need)
    • The code in the <script> tag in the HTML file or in the JS file referenced by SRC is synchronously loaded and executed ( newer browsers can load parallel to the blocked JS, but the execution is still synchronous )
    • The code in the <script> tag in the HTML file is executed asynchronously using the JS file introduced by the document.write () method
    • The HTML file in the <script> tag src attribute referenced by the JS file in the code is then used document.write () method introduced by the JS file is synchronous execution
    • Asynchronously preloading a JS file using an Image object (will not be executed, the OnLoad event will not fire, but will trigger OnError)

Do not use this approach like this, which does not initiate a request to load the JS file:

divnode.innerhtml = ' <script src= ' xxx.js ' ></script> ';

The Window.onload event is triggered when the JS file is loaded (even if it is loaded asynchronously, and the page in the IFRAME is loaded)

Whether the script tag directly embed the code or the introduction of JS file, the script tag's JS code is to parse a paragraph and then execute a paragraph, so do not appear similar to the previous script tag in the code to use the variable, in the code of the latter tag to define the wrong way.

=====================================================

1.

<script>

Code to execute synchronously load

</script>

2.

<script src= "Xx.js" ></script>//synchronous loading code in execution Xx.js

Because it is synchronous, you can use Document.wirte (), such as JSONP, to embed a JS file, fetch the data from the server and write the contents to the document with the server script output JS code.

3.

<script>

document.write (' <script src= ' xx.js ' ><\/script> '); Asynchronously loading code in the execution xx.js

</script>

4.

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

The following code is in the Xx.js:

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

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

Then the Xx.js and 11.js, 22.js are synchronously loaded and executed.

If Xx.js, 11.js, and 22.js are loaded asynchronously with the Insert Script node, then 11.js and 22.js are loaded asynchronously,

If Xx.js is loaded asynchronously as a script node, 11.js and 22.js are loaded in document.write (script), then 11.js and 22.js are synchronously loaded (with the latest browser tests, under Chrome, XX.J The step load execution has not been able to write to the document using document.write (), but if you do not insert the file loading process and use document.write () to open the rewrite of the page before inserting, the asynchronous-loaded JS can still write to the content, such as the previous page The onclick callback function of the button is inside document.write (1), then Headnode.appendchild (Scriptnode), but Firefox and IE can be written before the document is closed (by Xx.js Alert block document off))

Test: Alert (in 11.js) (The best way is to use the server script output JS code, delay Iao a few seconds before the output, such as Php:sleep (5); Do not use a For loop, the JS engine is single-threaded execution, continuous execution of any piece of code will cause the rest of the code is blocked) , 22.js in Console.log (), you can see that the code in 22.js is blocked.

5.

In this way, xx.js asynchronously loads execution after appendchild executes

var script = document.createelement ("script");

Script.setattribute ("src", "xx.js");

Documenrt.getelementsbytagname ("Head") [0].appendchild (script);

6. Asynchronously pre-load JS file with Image object (will not be executed)

The src of the image is assigned the request, and the file type is not picky (the picture may also have a script dynamically created, such as verification code), so the JS file can be assigned to the URL image.src, JS loaded by the browser cache.

var img = new Image (); Img.onload = function () {alert (1);}; Since the JS file returned by MIME  is not a picture, the onload callback function will not be triggered img.src = ' http://localhost/test/loadjs/try.2.js '; var s = Document.createelement ("script"), var h = document.getelementsbytagname ("Head") [0];//execution jss.src=img.src; H.appendchild (s);

A bit of a problem when detecting file loading, you can use nonstandard image.complete, which is false (even if onerror is true) in Chrome and Firefox only when the file is loaded, and the TR after onload in IE9 UE, does not start loading, loading process, load failure is false, under IE8 and IE8, OnLoad is still false, you need to set the delay detection to detect true, in addition, IE picture object after loading, regardless of success, will get a placeholder picture size, you can This size is checked to see if the execution of the loading process has been completed (either onerror or onload).

var im = new Image (); Console.log ([1,im.complete,im.width,im.readystate]); im.onerror=im.onload = function (event) {     var e = event| | window.event;        var eventtype = E.type;        var host = this;    Console.log ([' Callback ', EventType, Host.complete,host.width,host.readystate]);    SetTimeout (function () {//For ie8-        console.log ([' Callback Delay ', EventType, Host.complete,host.width, Host.readystate]);    },100); }im.src= "Http://seajs.org/dist/sea.js"; Console.log ([1,im.complete,im.width,im.readystate]);

In IE, the image object has a onreadystatechange event that executes only after the picture is successfully loaded and the JS file does not trigger the event

var im = new Image (); Console.log ([Im.complete, Im.readystate]); False,uninitialized Im.onreadystatechange = function () {   Console.log ([Im.complete, Im.readystate]);//false, Complete    setTimeout (function () {           Console.log ([Im.complete, Im.readystate]);//true,complete     },100);} IM.SRC = "Http://www.baidu.com/img/baidu_sylogo1.gif";

A function to load the JS file:

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.type = "Text/javascript";   Head.appendchild (script); script.onload = Script.onreadystatechange = function () {//script tag, IE onreadystatechange Events, with the OnLoad event standard     
File loading is not successful onload does not execute,//(!this.readystate) is for the standard, IE 9 also supports the standard onload if ((!this.readystate) | | this.readystate = = "Complete" | | This.readystate = = "Loaded") { callback (); } } End onReadyStateChange}
script.src = URL;   

For the 4th Test (synchronous loading) (where Insert alert is easy to see when loading is blocked)

Tryjs.html

<! DOCTYPE html> 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

Console.log (' Write begin ');d ocument.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> ');d ocument.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

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

Try.2.js

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

test Results (callback complete of file 2 and file 1 are not determined 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

========= Several test files (this is the most recently measured) ============

Files in/test/loadjs/

Http://files.cnblogs.com/ecalf/loadjs.rar

Original posts: http://www.cnblogs.com/ecalf/archive/2012/12/12/2813962.html

Synchronous loading and asynchronous loading of Javascript files

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.