0

How can I add native javascript into $.when? I get an error for doing this below when I want to use for each inside $.when. Any ideas?

var scripts = [
    "ccommon.js",
    "ccommon2.js",
    "ccommon3.js"
];

$.when(
    // Via $.getScript.
    for(var i = 0; i < scripts.length; i++) {
        $.getScript(scripts[i]);
    }
).done(function(){

    //place your code here, the scripts are all loaded.
    alert('script loaded');

});
Run
  • 54,938
  • 169
  • 450
  • 748
  • 2
    When you call a function, the arguments must be a list of *expressions*, i.e. `foo(expr1, expr2, ...)`. You cannot put a *statement* there. – Felix Kling Jul 11 '13 at 09:48

1 Answers1

2

You need to pass the list of promise objects as as argument list like $.when(p1, p2, p3).then(function()) since in this case you have an dynamic list, you can use .apply() function invoke the $.when() which the dynamic list of parameters

var array = [];
for(var i = 0; i < scripts.length; i++) {
    array.push($.getScript(scripts[i]));
}

$.when.apply($, array).done(function(){

    //place your code here, the scripts are all loaded.
    alert('script loaded');

});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531