Skip to content Skip to sidebar Skip to footer

Async Loading Js Scripts - Guarantee They Load In Right Order

I'm trying to load my js files asynchronously, with the code: function load_js() { var scripts = [ 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js',

Solution 1:

Try this. It is using the method from http://msdn.microsoft.com/en-us/library/ie/hh180173%28v=vs.85%29.aspx to attach to the event called once a script is loaded.

functionload_js() {
    var scripts = [
        'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js',
        'http://code.jquery.com/ui/1.10.2/jquery-ui.min.js',
        '/js/libs/joose.min.js',
        '/js/observer.js',
        '/js/resume-library.js'
    ];


    functionloadNext(){
        var src = scripts.shift();
        if (typeof src === 'undefined')
           return;

        var s = document.createElement("script");

        s.src=src;
        if(s.addEventListener) {
          s.addEventListener("load",loadNext,false);
        } 
        elseif(s.readyState) {
          s.onreadystatechange = loadNext;
        }
        document.body.appendChild(s);
       }
    }

   loadNext();
}

Solution 2:

This is not tested but should be the solution ,

i made a function that sets the src and appends the script and triggers a callback, then i have a function that continues looping through scripts only when the callback triggers, so this way it should be the same order

functionappendScript(src,callback){
        var element = document.createElement("script");
       element.src = src;
       document.body.appendChild(element);

       element.onload=function(){
        callback();
       }
}


var i = 0;
var loopScripts = function(scripts) {
    appendScript(scripts[i],function(){
        // set i to next item when callback gets called
        i++;

        // any more items in array? continue loopif(i < scripts.length) {
            loopScripts(scripts);   
        }
    }); 
}



functionload_js() {
   var scripts = [
       'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js',
       'http://code.jquery.com/ui/1.10.2/jquery-ui.min.js',
       '/js/libs/joose.min.js',
       '/js/observer.js',
       '/js/resume-library.js'
   ];

   //start the looploopScripts(scripts);
}

tested it, this works pretty fine ! but you need to implement the case if the script is not available -> because then the loop wont continue

Post a Comment for "Async Loading Js Scripts - Guarantee They Load In Right Order"