I need a method to fetch different scripts with a callback. This method works ok:
fetchScripts:function() {
var _this=this;
$.when(
$.ajax({
url:_this.url + 'library/script-one.js',
type:'get',
cache:true
}),
$.ajax({
url:_this.url + 'library/script-two.js',
type:'get',
cache:true
}),
{ .... },
$.ajax({
url:_this.url + 'library/script-n.js',
type:'get',
cache:true
})
).then(function() {
console.log('fetch is done');
})
},
But i'd like to more generalize the method because redundany is increasing. Is it possible to pass a promise to $.when()? Below my first attempt - but url is always the same, i.e. 'script-n.js' Maybe i missed the point and you could illustrate a more "beauty" solution
fetchScripts:function() {
this.deferred=new $.Deferred();
this.promise=this.deferred.promise();
var _this=this;
$.each([
'script-one.js',
'script-two.js',
( .... ),
'script-n.js'
],function() {
_this.script=this;
_this.promise.then(function(){
return $.ajax({
url:_this.url + 'library/' + _this.script,
type:'get',
cache:true
})
});
});
$.when(
this.promise
).then(function() {
console.log('fetch is done');
});
this.deferred.resolve();
},