1

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
user1014412
  • 359
  • 1
  • 2
  • 15

1 Answers1

0

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
});
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • From what i understand the mapping already fetches the scripts, right? I also had this idea but wasn't sure whether this was the right way to go, because of `$.when()` to watch and wait for all loadings to complete. But after some more thinking i understood that in my example and yours the arguments to `$.when()` are allways the return values of every `$.getScript()` call. What i don't understand yet are your two `$.then()` statements and esp. not why and what you are returning there. Would you mind to add more comments to clarify what is going on there? – user1014412 Mar 01 '15 at 18:37
  • Why are you using two chained `.then()` handlers. There's nothing available in the first one that isn't available in the second and there's no async between them. – jfriend00 Mar 01 '15 at 22:12
  • Two `.then()`s are indeed not strictly necessary. Written this way, the first `.then()` serves as an adaptor, allowing the second `.then()` to receive results in "standardized" form - "an array of fulfillment values" - as described in [this draft standard](https://github.com/domenic/promises-unwrapping). Thus, there is some sort of logic to this double-then pattern. – Roamer-1888 May 05 '15 at 22:39