Skip to content

Instantly share code, notes, and snippets.

@SleepWalker
Forked from db/jquery.ajax.progress.js
Last active August 29, 2015 14:11
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 SleepWalker/d1681dfc181bd2240cd6 to your computer and use it in GitHub Desktop.
Save SleepWalker/d1681dfc181bd2240cd6 to your computer and use it in GitHub Desktop.
(function addXhrProgressEvent($) {
// Patch for progress event support
var originalXhr = $.ajaxSettings.xhr;
$.ajaxSetup({
progress: $.noop,
xhr: function() {
var xhr = originalXhr(), that = this;
if (xhr) {
if (typeof xhr.addEventListener == "function") {
xhr.addEventListener("progress", function(event) {
that.progress(event);
if (that.global) {
var event = $.Event('ajaxProgress', event);
event.type = 'ajaxProgress';
$(document).trigger(event, [xhr]);
}
},false);
}
}
return xhr;
}
});
})(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