如何将 jQuery.when() 与 URL 数组一起使用?

How to use jQuery.when() with an array of URLs?

我将如何更改此示例

$.when(
   $.getScript( "/mypath/myscript1.js" ),
   $.getScript( "/mypath/myscript2.js" ),
   $.getScript( "/mypath/myscript3.js" ),
   $.Deferred(function( deferred ){
      $( deferred.resolve );
   })
).done(function() {
   //place your code here, the scripts are all loaded
});

当我不知道要加载的脚本的确切数量并改用 URL 数组时?

var urls = [
   '/url/to/script1.js',
   '/url/to/script2.js',
   '/url/to/script3.js',
   '/url/to/script4.js'
];

由于上面的示例是带参数的函数调用,我不能使用像 $.each() 这样的循环,可以吗?另外,我知道 Function.apply,但不知道如何从将简单参数数组传递给函数转变为将函数调用数组传递给函数。

您将使用 .apply 然后使用 arguments:

var urls = [
   '/url/to/script1.js',
   '/url/to/script2.js',
   '/url/to/script3.js',
   '/url/to/script4.js'
];

var requests = urls.map(function(url){ return $.getScript(url); });
$.when.apply($, requests).then(function(){
    console.log(arguments); // logs all results, arguments is the results here
    return [].slice.call(arguments);
}).then(function(arr){
     // access as an array
});