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

自闭症网瘾萝莉.ら 提交于 2019-12-11 11:56:39

问题


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


来源:https://stackoverflow.com/questions/28796758/how-to-use-jquery-when-with-an-array-of-urls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!