Parallel loading and sequential execution of JS

Source: Internet
Author: User

Re-review the next section of the content, found that the compatibility of the browser is really big head, processing is very troublesome.

Now summarize the method of parallel loading multiple JS:

1, for the dynamic createelement (' script ') method, all browsers are asynchronously parallel loaded. What we mean by parallelism here is not just about

JS parallel loading, also includes JS and other resources than slices, iframe loading. But this way in Firefox's 2.0 3.0 3.1 version and opera 9.63

can be executed sequentially. But because of Kyle's offer, modern browsers can set the properties of a dynamically created script element Async=false

JS sequential execution.

2, can be document.write (' <script> ') way to parallel loading (IE8 and above, modern browser) and sequential execution.

3, Load JS via XHR. But with the same-origin restrictions, so for the external JS file or the CDN JS on the powerless.

The Type property of the 4,<script> is set to the "Script/cache" non-standard type property, so that the JS file will only be loaded and not executed. When you need to do this, create a type

The property is "Text/javascript" normal <script> elements, SRC is set to the previous loaded JS address, the execution sequence developer controllable (execution timing is also fully

controllable). In a similar way there are pre-loaded by .

Already some Daniel, like the one mentioned earlier, has provided a standard library of compatible browsers, and the project name is LABJS.

I wrote a simple plugin that is not currently tested on ie6,7.


        if(!asynchelper)varAsynchelper = {}; Asynchelper.cache= [];//storing the obtained JS objectAsynchelper.createajax= (function(){            if(' XMLHttpRequest 'inchwindow) {                return function(){                    return NewXMLHttpRequest (); }            }Else{                varI= 0,len, FNS = [function(){return NewActiveXObject (' Microsoft.XMLHTTP ')},function(){return NewActiveXObject (' Msxml2.xmlhttp ')},                    function(){return NewActiveXObject (' msxml2.xmlhttp.3.0 ')},function(){return NewActiveXObject (' msxml2.xmlhttp.6.0 ')}];  for(len = fns.length;i<len;i++){                    Try{fns[i] (); returnFns[i];  Break; }Catch(e) {}}}        })(); //function function, asynchronous XHR loading JS, parallel random loading JS and other resources, need to be sequential control, and subject to the same origin,        //cannot use CDN or external reference JSASYNCHELPER._LOADJSWITHXHR =function(url,fn,inorder) {inorder= Inorder | |true;//Default Order Loading            varJsobj = {file:NULL, isLoaded:false, CALLBACK:FN},XHR, I,len;            AsyncHelper.cache.push (Jsobj); XHR= This. Createajax (); Xhr.onreadystatechange=function(){                if(Xhr.readystate = = 4){                    Try{                        if(Xhr.status >=200 && Xhr.status < | | xhr.status = = 304) {Jsobj.file= Xhr.responsetext;//The returned JS is stored in the object                            if(inorder) { for(i=0,len=asynchelper.cache.length;i<len;i++){                                    if(!asynchelper.cache[i].file) {                                        //avoid repeatedly parsing already loaded JS files                                        //to delete a file that has already been loaded from a buffer rollup                                        if(i>0) {AsyncHelper.cache.splice (0, i); }                                         Break; }Else{                                        //function equals global eval, does not change scope chain                                        NewFunction (Asynchelper.cache[i].file) (); FN&& fn ();//Execute callback function                                        if(i = = len-1) {Asynchelper.cache= [];//Empty Cache                                        }                                    }                                } }Else{                                if(jsobj.file) {eval (jsobj.file);                                FN (); }                            }                        }                    }Catch(loaderror) {setTimeout (function(){                            Throw(NewError (' Loading with XHR response error--' +loaderror)) },0);            }                }            }; (' Get ', URL); Xhr.setrequestheader (' X-request-with ', ' XMLHttpRequest '); Xhr.send (NULL);        }; //asynchronously loads JS by creating a SCRIPT element that supports cross-domain. Under Firefox,opera is also the sequential loading. Asynchelper._loadjswithdomelement =function(URL,FN) {varDom = document.createelement (' script '); Dom.type= ' Application/javascript '; Dom.async=false; DOM.SRC=URL; dom.isloaded=false; //Execute callback function, use ONREADYSTATECHANGE,W3C with onload under IE            if(' onload 'inchDOM) {Dom.onload=fn; }Else{Dom.onreadystatechange=function(){                    if(Dom.readystate = = ' Loaded ' | | dom.readystate = = ' complete ') &&!dom.isloaded)                        {fn (); dom.isloaded=true; }}} document.getelementsbytagname (' head ') [0].appendchild (DOM); }        //script for parallel loading is inserted by document.write. GTE IE8 and Opera support.         //all browsers support the sequential loading of JS in this wayAsynchelper._loadjswithscripttag =function(URL,FN) {Document.writeln (' <script type= ' application/javascript "src=" ' +URL+ ' ><\/script> '); //binding the OnLoad event to a window            if(Window.addeventlistener) {Window.addeventlistener (' Load ', FN,false); }Else{window.attachevent (' OnLoad ',function() { ( This, window.event); })            }        }        //exposing the external interface, loading a single JS fileAsynchelper.loadscript =function(URL,FN) { This. _loadjswithdomelement (URL,FN); }        //loading multiple JS filesAsynchelper.loadscripts =function(URLS,FN) {functionissamedomain (URL) {varDomain = Document.location.protocol + "//" +Document.location.hostname+ "/"; if(Url.indexof (' http ')!==-1 | | url.indexof (' HTTPS ')!==-1){                    if(Url.indexof (domain)!==-1){                        return true; }                    return false; }                return true; }            //If the URL is homologous, use XHR to load            varI,len,flag,loadmethod;  for(i=0,len=urls.length;i<len;i++){                if(flag = Issamedomain (Urls[i]))Continue; Else  Break; }            //Default XHR loadLoadmethod =asynchelper._loadjswithxhr; if(!flag) {                //Firefox opera is loaded using DomElement mode to ensure sequential and asynchronous loading                //This feature is also not supported by the latest version of Firefox, as tested.                 //Firefox 4 for the HTML5 standard, once in the developer version removed the dynamic creation <script> to load JS file execution sequence support:                //<script> elements created using document.createelement () and inserted into a document now behave                //according to the HTML5 specification by default. Scripts with the SRC attribute                //execute as soon as available (without maintaining ordering) and scripts without                //The src attribute execute synchronously.                //Kyle protested to the WebKit development team, raised a bug and finally got the support he wanted:                //script-inserted scripts that has the SRC attribute execute in the insertion order,                //set. Async=false on them.                if(Navigator.userAgent.toLowerCase (). IndexOf (' Firefox ')!! =-1 | | navigator.userAgent.toLowerCase (). IndexOf (' opera ')! =-1) Loadmethod=asynchelper._loadjswithdomelement; ElseLoadmethod=Asynchelper._loadjswithscripttag; } Loadmethod=asynchelper._loadjswithdomelement;  for(i=0;i<len;i++){                if(i = = len-1) { (ASYNCHELPER,URLS[I],FN); }Else{ (asynchelper,urls[i]); }            }        }//Sample Code
Asynchelper.loadscripts ([' Http:// ', './a.js ', './b.js '],function () { Console.log (' Success ')})

Parallel loading and sequential execution of JS

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: 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.