You can simply construct an array of AJAX promises instead. After that, use $.when.apply($, <yourArray>)
. To illustrate the solution, here is an example based on the code you have provided:
// Construct array to store requests
var requests = [];
// Conditionally push your deferred objets into the array
if(var1) requests.push($.getJSON(url1, function(data) {...}));
if(var2) requests.push($.getJSON(url2, function(data) {...}));
if(var3) requests.push($.getJSON(url3, function(data) {...}));
// Apply array to $.when()
$.when.apply($, requests).then(function() {
// Things to do when all is done
});
What that in mind, here is a code snippet that shows a proof-of-concept example: I am using dummy JSON returned by JSONPlaceholder:
$(function() {
// Construct array to store requests
var requests = [];
// Conditional vars
var var1 = true,
var2 = false,
var3 = true;
// Conditionally push your deferred objets into the array
if (var1) requests.push($.get('https://jsonplaceholder.typicode.com/posts/1', function(data) { return data;
}));
if (var2) requests.push($.get('https://jsonplaceholder.typicode.com/posts/2', function(data) { return data;
}));
if (var3) requests.push($.get('https://jsonplaceholder.typicode.com/posts/3', function(data) { return data;
}));
// Apply array to $.when()
$.when.apply($, requests).then(function(d) {
// Log returned data
var objects = arguments;
console.log(objects);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>