How to make a real progress bar of a jQuery Ajax load request?
I need an animated progress bar (like on YouTube), but not plugins!
My ajax request looks like this:
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
//Download progress
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
console.log(evt);
var percentComplete = evt.loaded / evt.total * 100;
//Do something with download progress
// this is a static animation but i'm not able to make it work with the precentComplete that i have.
$({
property: 0
}).animate({
property: 105
}, {
duration: 4000,
step: function() {
var _percent = Math.round(this.property);
$('#progress').css('width', _percent + "%");
if (_percent == 105) {
$("#progress").addClass("done");
}
},
complete: function() {
alert('complete');
}
});
}
}, false);
return xhr;
},
type: method,
url: rest_api,
headers: headers,
timeout: 10000,
dataType: 'json',
data: http_content,
beforeSend: function(xhr) {
// do stuff
},
success: function(data, status, xhr) {
// do stuff
},
error: function(xhr, e) {
// do stuff
}
});
So, I already have an animation, but I couldn't relate to reality, it is a static animation, but I cannot get it to work with the precentComplete I have in the progress event.
Any ideas please? I need more clarification on this XHR2 with a working snippet or example for better understanding.
The animation looks like this: jsFiddle
source to share
My first shot would be to define the progress bar outside of the "progress" event handler, and then set the width property from the event handler.
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
var progressBar = $("#progress");
//Download progress
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
console.log(evt);
var percentComplete = /* compute it */;
progressBar.style("width", percentComplete + "%");
}
}, false);
return xhr;
},
...
});
It seems that not every browser allows you to track download progress, which is easy, you can find more information on how to actually calculate progress here: AJAX Page Download progress
source to share