High-performance javascript: Loading and running (dynamically loading JS code)

Source: Internet
Author: User

How the browser is loading JS
when the browser encounters a <script> tag, the browser first downloads the JavaScript code based on the tag src attribute and then runs the JavaScript code, which then continues to parse and translate the page. If you need to load a lot of JS file, it will make people feel the page loading is slow, affecting the interaction of the page. The browser will not render any part of the page before it encounters <body>, if the JS file that needs to be loaded in

Internet Explorer 8, Firefox 3.5, Safari 4, and Chrome 2 allow JavaScript files to be downloaded in parallel. This indicates that when a script file is being downloaded, other script downloads are not blocked. Parallel download script speeds up script download time, but still blocks downloads for other resources.

Solution Solutions
1. Place the script at the bottom of the page
A common practice is to put the <script> tag before the closed </body>. This allows the page to be displayed to the user first, so that the page loading speed is not very slow. It's a good idea to put the CSS file in the head and load the DOM while rendering the style.

2. Group Download Script
We know that multiple HTTP requests can also degrade page performance. So we can combine multiple script files into a single file download. This reduces the HTTP request, but this adds a lot of extra work to us because each time we publish we merge the files. To do this, we can use a group download method to achieve the goal. A group download is a request to download more than one script file at a time. For example, the following URL: http:www.abc.com/combo.do?file1.js&file2.js each time a fixed service request to the server downloads multiple files. The server merges multiple files together and returns them to the client. This is the best way for an HTML page to contain multiple external JavaScript.

3. Delay Loading
If the script file is big and large, then I'm afraid how we can compress the file how to reduce the number of HTTP requests, script loading will lock the browser for a large period of time. The better way to do this is to wait for the page to load and then load the script, that is, after the Window.onload event is issued, download the code.   the Defer property in HTML4 can be implemented without blocking the browser's other processing when the script is downloaded, and will not be executed after the code is downloaded, but not until the DOM is loaded (before the window.onload is completed). But the defer property is supported only by ie4+ and ff3.5+, which is not supported by other browsers, so this is not an ideal cross-browser solution.   one common way to delay loading is to dynamically create script elements. A new <script> element can be created very easily through standard DOM functions:  
var script = document.createelement ("script");
Script.type = "Text/javascript";
script.src = "Xxx.js";
document.getElementsByTagName ("Head") [0].appendchild (script);
when the script element is added to the page, it starts downloading the scripts file. The advantage of this technology is that no matter where the download is initiated, the download and operation of the file will not block the other page processing processes. When the script file is downloaded, the returned code is usually executed immediately (in addition to FF and opera, they will wait for all previous dynamic script nodes to complete. )

The problem occurs when the dynamically loaded script is simply an interface for other script calls. Because the calling code does not know whether the called interface is ready to complete. But fortunately, the mainstream browser is now able to track whether the node is loaded.

FF, Opera, Chrome and safari3+ will issue a load event after the node is received, IE is emitting a readystatechange event,<script> element has a readystate attribute, Its value changes with the download process. ReadyState has 5 values: uninitialized (default state), loading (download start), loaded (download complete), interactive (download completed but not yet available), complete (all data is ready). Microsoft documentation says that these values may not all appear, sometimes the script will get loaded does not appear complete, sometimes the script will be completed does not appear loaded. The safest thing to do is to check both states in the ReadyStateChange event, and when one of the two states is present, delete the ReadyStateChange handle to prevent the event from being executed two times.

according to the above description, the new dynamic loading code looks like this:

function Loadscript (URL, callback) {
var script = document.createelement ("script");
Script.type = "Text/javascript";
if (script.readystate) {//IE
Script.onreadystatechange = function () {
if (script.readystate = = "Loaded" | | script.readystate = = "complete") {
Script.onreadystatechange = null;
Callback ();
}
};
}else{//FF, Chrome, Opera, ...
Script.onload = function () {
Callback ();
};
}
script.src = URL;
document.getElementsByTagName ("Head") [0].appendchild (script);
}
if you want to load multiple files, and you want to guarantee the order, you can do this by concatenating the above functions.

take a look at the following usage examples:

Loadscript.js: Implementing the Loadscript function
page File:
    <meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title> Dynamic Loading </title>
<script type= "Text/javascript" src= ". /scripts/loadscript.js "></script>
<script type= "Text/javascript" >
Loadscript (".. /scripts/test1.js ", function () {
Loadscript (".. /scripts/test2.js ", function () {
Loadscript (".. /scripts/test3.js ", function () {
Test3.print ("Hi, i ' m abc.");
})
});
});
</script>
<body>
</body>
test1.js for testing:


the test2.js,test2 used for testing relies on test1:

var test2 = { print:function (msg) { test1.print (msg); alert ("from test2:" + msg);     } };
the TEST3.JS,TEST3 used for testing relies on Test2:

var test3 = { print:function (msg) { test2.print (msg); alert ("from test3:" + msg);     } };
The run page will have a popup "from Test1:hi, I ' m abc.", "from Test2:hi, I ' m abc.", "from Test3:hi, I ' m abc."

Dynamic Script loading is the most commonly used JavaScript non-blocking download method because it is cross-browser and easy to use.

XMLHttpRequest Script Injection
use the Xhr object to download the JavaScript code and then dynamically create the script element to inject the JavaScript code into the page.

This method requires Ajax, first of all, the Ajax auxiliary methods are listed:

/**
* Create Xmlhelper
* */
(function (window) {
var Xhrhelper = (function () {
var xhrhelper = function () {};
Xhrhelper.extend = function () {
var len = arguments.length, target = this;
for (var i = 0; i < len; i++) {
var source = Arguments[i];
For (var p in source) {
if (target[p] = = undefined) {
TARGET[P] = source[p];
}else{
throw new error ("Extend error:" + P + "is already existed.");
}
}
}
};
return xhrhelper;
})();
Window.xhrhelper = Xhrhelper;
}) (window);

/**
* Extend Xmlhelper
* */
Xhrhelper.extend ({
/**
* Create XMLHttpRequest object.
* */
Createxmlhttp:function () {
var xmlhttp;
/* @cc_on
@if (@_jscript_version >= 5)
try{
XMLHTTP = new ActiveXObject ("Msxml2.xmlhttp");
} catch (e) {
try{
XMLHTTP = new ActiveXObject ("Microsoft.XMLHTTP");
} catch (E) {
XMLHTTP = false;
}
}
@else
XMLHTTP = false;
@end
@*/
if (!xmlhttp && typeof XMLHttpRequest! = ' undefined ') {
try{
XMLHTTP = new XMLHttpRequest ();
} catch (e) {
XMLHTTP = false;
}
}
return XMLHTTP;
},
/**
* Send request.
* */
Req:function (options) {
var defaults = {
Method: "Get",//Get,post,put,delte
Url:null,
Data:null,
Async:true,
Username:null,
Password:null,
Onloading:function (XHR) {},
Onloaded:function (XHR) {},
Oninteractive:function (XHR) {},
Oncomplete:function (XHR) {},
Onabort:function (XHR) {},
Onerror:function (XHR) {}
};
For (var p in options) {
DEFAULTS[P] = options[p];
}
var xmlhttp = xhrhelper.createxmlhttp ();
if (XMLHTTP) {
Xmlhttp.onreadystatechange = function () {
if (xmlhttp.readystate = = 1) {//not initialized
Defaults.onloading (XMLHTTP);
} else if (xmlhttp.readystate = = 2) {//initialized
Defaults.onloaded (XMLHTTP);
} else if (xmlhttp.readystate = = 3) {
Defaults.oninteractive (XMLHTTP);
} else if (xmlhttp.readystate = = 4) {
if (Xmlhttp.status = = 0) {
Defaults.onabort (XMLHTTP);
} else if (xmlhttp.status >= && xmlhttp.status <= | | xmlhttp.status = 304) {
Defaults.oncomplete (XMLHTTP);
} else{
Defaults.onerror (XMLHTTP);
}
}
};
if (defaults.username! = NULL && Defaults.password! = null &&
Defaults.username.length! = 0 && Defaults.password.length! = 0) {
Xmlhttp.open (Defaults.method, Defaults.url, Defaults.async,
Defaults.username, Defaults.password);
}else{
Xmlhttp.open (Defaults.method, Defaults.url, Defaults.async);
}
if (defaults.method.toLowerCase () = = "Get") {

}else if (defaults.method.toLowerCase () = = "Post") {
Xmlhttp.setrequestheader (' Content-type ', ' text/html; Charset=utf-8 ');
}
Xmlhttp.send (Defaults.data);
}
return XMLHTTP;
}
});
then the function that uses XHR to download JS file:
function xhrload (URL, callback) {
Xhrhelper.req ({
Method: "Get",
Url:url,
Oncomplete:function (XHR) {
var script = document.createelement ("script");
Script.type = "Text/javascript";
Script.text = Xhr.responsetext;
Document.body.appendChild (script);
Callback ();
}
});
}
the Xhrload function can be called in the page as follows:

xhrload (".. /scripts/test1.js ", function () { test1.print (" ABC "); });
The advantage of this approach is that you can download JavaScript code that is not executed immediately. Because the code is downloaded from the <script> tag, it is not executed immediately after it is downloaded. Another advantage is that almost all browsers support this approach.

the limitation of this approach is that JavaScript files must be placed in the same domain as the page. Because XMLHttpRequest cannot be accessed across domains.

third-party libraries
YUI
Lazyload
Labjs This article turns to excerpt: Http://ilanever.com/article/detail.do?id=264#page-catalog-4

(RPM) High-performance javascript: Loading and running (dynamically loading JS code)

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.