Search code examples
jquerygetscript

How to add native javascript into `$.when`?


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');

});

Solution

  • 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');
    
    });