Summary of methods for loading JS files asynchronously

Source: Internet
Author: User
Tags getscript

Method One, Jquery.getscript

HTML Code:

Code to copy code as follows
<button id= "Go" >Run</button>
<div class= "Block" ></div>

JQuery Code:

Jquery.getscript ("Http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js",
function () {
$ ("#go"). Click (function () {
$ (". Block"). Animate ({backgroundcolor: ' Pink '}, 1000)
. Animate ({backgroundcolor: ' Blue '}, 1000);
});
});

Method Three

Code to copy code as follows
Synchronous loading, single-step loading, the introduction of JS content can be directly used
var skip={};
Get XMLHttpRequest Object (provides protocol for client to communicate with HTTP server)
Skip.getxmlhttprequest=function () {
if (window. XMLHttpRequest)//other than IE browser
return new XMLHttpRequest ();
else if (window. ActiveXObject)//IE
return new ActiveXObject ("Msxml2.xmlhttp");
},
Import Content
Skip.includejstext =function (rootobject,jstext) {
if (rootobject! = null) {
var oscript = document.createelement ("script");
Oscript.type = "Text/javascript";
Oscript.id = sId;
OSCRIPT.SRC = FILEURL;
Oscript.defer = true;
Oscript.text = Jstext;
Rootobject.appendchild (Oscript);
alert (Oscript.text);
}
},
Import file
Skip.includejssrc =function (Rootobject, FILEURL) {
if (rootobject! = null) {
var oscript = document.createelement ("script");
Oscript.type = "Text/javascript";
OSCRIPT.SRC = FILEURL;
Rootobject.appendchild (Oscript);
}
},
Synchronous loading
Skip.addjs=function (rootobject, url) {
var oxmlhttp = Skip.getxmlhttprequest ();
Oxmlhttp.onreadystatechange = function () {//In fact, when the second call to import JS, because there is this *.js file in the browser, it is not the access server, it is not executing this method, This method is only used when it is set to asynchronous.
if (oxmlhttp.readystate = = 4) {//Www.111cn.net when execution completes (returns a response)
if (oxmlhttp.status = = | | oxmlhttp.status = 304) {//200 has read the corresponding URL file, 404 indicates that the file does not exist
SKIP.INCLUDEJSSRC (rootobject, URL);
} else{
Alert (' XML (www.111cn.net) Request error: ' + oxmlhttp.statustext + ' (' + oxmlhttp.status + ') ');
}
}
}
1.True means that the script will continue executing after the Send () method without waiting for a response from the server, and there is a call to onReadyStateChange () method in the open () method. By setting this parameter to "false", you can omit the extra onreadystatechange code, which indicates that the server returns a response before executing the method after send ().
2. Synchronous execution of the Oxmlhttp.send () method after the Oxmlhttp.responsetext has returned the corresponding content, and asynchronous or empty, only in oxmlhttp.readystate = = 4 o'clock only content, Anyway, the operation after Oxmlhttp.send () is equivalent to the operation of oxmlhttp.readystate = = 4, which is equivalent to only this state.
Oxmlhttp.open (' GET ', url, false); When the URL is JS file, IE will automatically generate ' <script src= ' *.js "type=" Text/javascript "> </scr ipt> ', FF will not
Oxmlhttp.send (NULL);
Skip.includejstext (Rootobject,oxmlhttp.responsetext);
}
};
var Rootobject=document.getelementbyid ("divID");
Skip.addjs (Rootobject, "test.js")//test.js file contains Funciotn test () {alert ("Test");}
Test ();//Even if it is called immediately, it will not go wrong.
</script>

Method Three, their own use of the load JS file, support multi-file, incompatible with IE

Code to copy code as follows

/**
* Load JS file
* @param {string | | array} URL JS path
* Callback after @param {Function} fn loading is complete
* @return {Object} Game Object
* @example
* GetScript ("Url.js", FN)
* GetScript (["Url-1.js", "Url-2.js"],FN)
*/
Game.getscript = (function () {
var cache = {};//internal cache under URL, next time do not request
return function (URL, fn) {
if ("string" = = = typeof (URL)) {
url = [url]; If not the array with a set
};
var i = 0,//cycle up
OK = 0,//loaded successfully several JS
Len = url.length,//altogether a few JS
Head = document.getElementsByTagName ("head") [0],
JS, _url,
create = function (URL) {//JS created
JS = document.createelement ("script");
Js.type = "Text/javascript";
js.src = URL;
Head.appendchild (JS);
Return JS;
};
for (; i < Len;) {
if (cache[encodeuricomponent ((_url = url[i++])]) {//If loaded
(++ok >= len && fn) && fn ();//If all JS is loaded, the callback is executed
Continue
}
Cache[encodeuricomponent (_url)] =!0;//Set Cache
JS = Create (_url);//JS Created
fn && (js.onload = function () {
if (++ok >= len) {//If all JS is loaded, the callback is executed
FN ();
}
});
};
Head = JS = _url = create = null;
return this;
}
})();

From:http://www.111cn.net/wy/js-ajax/58715.htm

Summary of methods for loading JS files asynchronously

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.