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

2019-08-08 21:00发布

问题:

How would i have to change this example

$.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
});

when i don't know the exact number of scripts to load and use an array of URLs instead?

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

As the above example is a function call with arguments I cannot utilize a loop like $.each(), can I? Also, I know about Function.apply, but don't know how to adapt from passing an array of simple arguments to a function to passing an array of function calls to a function.

回答1:

You'd use .apply and then get it with 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
});