我正在使用以下代码并行预加载某些文件:
$.when(
$.ajax({
url: "file1",
xhrFields: {
onprogress: function(e) {
if (e.lengthComputable) {
console.log(e.loaded / e.total * 100 + '%');
}
}
},
success: function() {
}
}),
$.ajax({
url: "file2",
xhrFields: {
onprogress: function(e) {
if (e.lengthComputable) {
console.log(e.loaded / e.total * 100 + '%');
}
}
},
success: function() {
}
}),
$.ajax({
url: "file3",
xhrFields: {
onprogress: function(e) {
if (e.lengthComputable) {
console.log(e.loaded / e.total * 100 + '%');
}
}
},
success: function() {
}
})
).then(function() {
//all files are downloaded
});
总下载大小为22MB。我正在寻找一种结合所有下载进度的方法,因此可以制作进度条。 例如,如果下载了总数的11MB,则应该给我50%。
在jQuery中甚至有可能吗?有提示吗?
更新:
好的,所以我设法得到了想要的东西,但是它不是很漂亮,感觉像是不好的编码。有人知道更好的方法吗?
var totalSizeFile1;
var totalSizeFile2;
var totalSizeFile3;
var loadedFile1;
var loadedFile2;
var loadedFile3;
function downloadFiles() {
$.when(
$.ajax({
url: "file1",
xhrFields: {
onprogress: function(e) {
if (e.lengthComputable) {
totalSizeFile1 = e.total;
loadedFile1 = e.loaded;
totalProgress();
}
}
},
success: function() {},
error: function(request, status, error) {}
}),
$.ajax({
url: "file2",
xhrFields: {
onprogress: function(e) {
if (e.lengthComputable) {
totalSizeFile2 = e.total;
loadedFile2 = e.loaded;
totalProgress();
}
}
},
success: function() {},
error: function(request, status, error) {}
}),
$.ajax({
url: "file3",
xhrFields: {
onprogress: function(e) {
if (e.lengthComputable) {
totalSizeFile3 = e.total;
loadedFile3 = e.loaded;
totalProgress();
}
}
},
success: function() {},
error: function(request, status, error) {}
})
).then(function() {
//all files are downloaded
});
}
function totalProgress()
{
totalSize = totalSizeFile1 + totalSizeFile2 + totalSizeFile3;
totalLoaded = loadedFile1 + loadedFile2 + loadedFile3;
totalProgress = Math.round(totalLoaded/totalSize * 100);
}