Skip to content

Instantly share code, notes, and snippets.

@mech
Forked from db/jquery.ajax.progress.js
Created July 5, 2016 11:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mech/c4dd04ffb432875abf04ced10f65dcc3 to your computer and use it in GitHub Desktop.
Save mech/c4dd04ffb432875abf04ced10f65dcc3 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.");
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment