Skip to content

Instantly share code, notes, and snippets.

@db
Created May 11, 2011 12:43
Show Gist options
  • Save db/966388 to your computer and use it in GitHub Desktop.
Save db/966388 to your computer and use it in GitHub Desktop.
add XHR2 progress events to jQuery.ajax
(function addXhrProgressEvent($) {
var originalXhr = $.ajaxSettings.xhr;
$.ajaxSetup({
progress: function() { console.log("standard progress callback"); },
xhr: function() {
var req = originalXhr(), that = this;
if (req) {
if (typeof req.addEventListener == "function") {
req.addEventListener("progress", function(evt) {
that.progress(evt);
},false);
}
}
return req;
}
});
})(jQuery);
// usage:
// note, if testing locally, size of file needs to be large enough
// to allow time for events to fire
$.ajax({
url: "./json.js",
type: "GET",
dataType: "json",
complete: function() { console.log("Completed."); },
progress: function(evt) {
if (evt.lengthComputable) {
console.log("Loaded " + parseInt( (evt.loaded / evt.total * 100), 10) + "%");
}
else {
console.log("Length not computable.");
}
}
});
@kosso
Copy link

kosso commented Mar 9, 2015

Hi,
Really useful patch. Thanks!

But how can I detect if this patch has already been applied in another js script on a page?
eg: I might have two plugins which included this patch. The second time this is included, it seems to break it.

Cheers!

@kelvinpalves
Copy link

Muito Bom!

@likerRr
Copy link

likerRr commented Aug 28, 2015

I made a plugin, that adds support of progress promise

Copy link

ghost commented Sep 29, 2015

Please how use it ?

@shahzadthathal
Copy link

shahzadthathal commented Apr 20, 2017

Hi,

What does it mean? " Length not computable."
How will it work in jquery-3.1.1?

Thanks

@zalaks
Copy link

zalaks commented May 9, 2018

Not working for me on cpanel server :-(

I have tried with exactly what u have given. However, this worked in localhost !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment