执行以下操作:
function loadArray(array, batchSize, callback) {
var length = array.length
batchSize = length < batchSize ? length : batchSize; // minimum
var batch = array.slice(0, batchSize); // the current batch
array = array.slice(batchSize); // the rest of the array
loadBatch(batch, function (results) {
if (array.length) { // there are more batches to process
// load the rest of the array
loadArray(array, batchSize, function (nextResults) {
// merge the results - recursion handles the rest
callback(results.concat(nextResults));
});
} else callback(results); // last batch
});
}
loadBatch
功能如下:
function loadBatch(batch, callback) {
var completed = 0;
var length = batch.length;
var results = new Array(length); // the array of results
$.each(array, function (index, element) {
$.ajax(element, {
complete: function (xhr, status) {
// save the results
results[index] = {
xhr: xhr,
status: status
};
if (++completed === length) callback(results); // done
}
});
});
}
现在您可以按如下方式加载资源:
loadArray(["a.json", "b.txt", ...], 10, function (results) {
var a = JSON.parse(results[0]);
var b = results[1];
// and so on
});
就是这样。如果您有任何问题,请告诉我。