0

I have a dynamic list of scripts that needs to be loaded and the callback function calls another async function defined in the loaded external script.

A script object consists of {scriptUrl, property}

All scripts have a externalScriptFunction function defined, that take script['property'] as a parameter.

for(var i = 0; i < scripts.length; i++) {
   var script = scripts[i];

   $.getScript(script['scriptUrl'], function() {
      externalScriptFunction(script['property'], function someAsyncMethod() {
         ...
         ...
      });

   })

}

The issue I am having is that before the $.getScript callback is executed, the for loop has advanced to the next element and script['property'] is from a different element of the array.

How do I solve this issue?

  • Is there some way to pass a query parameter to the loaded script?
  • Or a way for the $.getScript to finish loading the script before moving to the next item?
  • Any other solutions?

Thanks!

pkrish
  • 2,229
  • 7
  • 22
  • 29

2 Answers2

1

just use closures - How do JavaScript closures work?

so for your example it should look like this:

for(var i = 0; i < scripts.length; i++) {

 var script = scripts[i];
 (function(script){
   $.getScript(script['scriptUrl'], function() {
      externalScriptFunction(script['property'], function someAsyncMethod() {
         ...
         ...
      });

   })
 })(script)
}

not sure if that code actually works, but i think you got the idea?

http://jsfiddle.net/vGgpW/

Community
  • 1
  • 1
llamerr
  • 2,997
  • 4
  • 29
  • 40
1

You should pass a callback function like this,

var loadedCallback = function(extraData) {
    return function(data, textStatus, jqxhr) {
        externalScriptFunction(extraData, function someAsyncMethod() {
         ...
         ...
      });
    }
}

for(var i = 0; i < scripts.length; i++) {
   var script = scripts[i];
   $.getScript(script['scriptUrl'], loadedCallback(script["property"]));

}

DEMO

Okan Kocyigit
  • 13,203
  • 18
  • 70
  • 129