Created
May 11, 2011 12:43
-
-
Save db/966388 to your computer and use it in GitHub Desktop.
add XHR2 progress events to jQuery.ajax
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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."); | |
} | |
} | |
}); |
added support for the global ajax events
(function addXhrProgressEvent($) {
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);
the problem is that it can be more than one request at a time, so the only one possibility is try to use xhr.responseURL
to indentify the requests
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!
Muito Bom!
I made a plugin, that adds support of progress
promise
Please how use it ?
Hi,
What does it mean? " Length not computable."
How will it work in jquery-3.1.1?
Thanks
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
Agree with susamcsx.
It works very fyn in mozzila, but in chrome, it instantly reaches to 100% no matter what file size is
if file is very large, even at that time it reached to 100 instantly.
Please help me to get out this situation, i am almost stuck now with problem from last 3 hours