views:

57

answers:

3

I have two arrays.

  1. A list of urls to JavaScript files that I am registering with $.getScript(url);
  2. A list of inline JavaScript commands to register with $("html").append(inline)

Any items in (2) may be dependant on any items in (1). Meaning that I have to be sure that all items in (1) have finished loading before any of (2) are registered.

I want to load all of (1) asynchronously... since it will be faster, but how do I ensure that all of these processes have finished before registering (2)?

A: 

you can add the (2) in the success handler of the ajax call.

Orbit
The problem is that there are multiple ajax calls. One for each file in (1).
SystemicPlural
in the success handler , it can look in array (2) for any relevant commands, if you want to go to the trouble of making some sort of association. sorry i can't brainstorm a better solution.
Orbit
+1  A: 

I think this way it should work:

var scripts = [
  {"src": "script1", "loaded": false},
  {"src": "script2", "loaded": false},
  {"src": "script3", "loaded": false},
]
var commands = ["cmd1","cmd2","cmd3"];

for (var i = 0, l = scripts.length; i<l; i++){
  (function (script){
    $.ajax({
      url: script.src,
      dataType: 'script',
      success: function (){

        for (var k = scripts.length; k--;){
          if (scripts[k].src === script.src){
            scripts[k].loaded = true;
          }
        }

        var allReady = true;
        for (var k = scripts.length; k--;){
          if (!scripts[k].loaded){
            allReady = false;
          }
        }
        if (allReady){
          /*execute your inline commands*/
        }
      }
    });
  })(scripts[i]);
}
madeinstefano
+1  A: 

This should in my opinion be solvable via jQuery's callback capacity; see succinct usage descriptions here, hope this helps.

EDIT: here's the actual code:

$.extend({myFunc : function(someArg, callbackFnk){
// load files here
var data = 'test';

// now call function for inline loading
if(typeof callbackFnk == 'function'){
  callbackFnk.call(this, data);
}}});

$.myFunc(someArg, function(arg){ */here goes inline load*/ });
hjhndr
Thanks for your input hjhndr. I think what you are suggesting is that I create a callback function that is called after the data is loaded. I don't think it will work though, because loading the files is only completed with their own callback ... of which there are multiple... The custom callback will execute too early.
SystemicPlural