-
-
Save nebirhos/3892018 to your computer and use it in GitHub Desktop.
add XHR2 upload and download progress events to jQuery.ajax
This file contains 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({ | |
xhr: function() { | |
var req = originalXhr(), that = this; | |
if (req) { | |
if (typeof req.addEventListener == "function" && that.progress !== undefined) { | |
req.addEventListener("progress", function(evt) { | |
that.progress(evt); | |
}, false); | |
} | |
if (typeof req.upload == "object" && that.progressUpload !== undefined) { | |
req.upload.addEventListener("progress", function(evt) { | |
that.progressUpload(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."); | |
} | |
}, | |
progressUpload: function(evt) { | |
// See above | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Found the bug, you want to replace:
var req = originalXhr(), that = this;
with:
var that = this;
var req = originalXhr.bind(that)()
The problem is that the original XHR, in 1.7.2 used this.isLocal to choose, but since it is undefined, it will do the right thing... in 1.11.3 there is another condition this.type to choose between ActiveXHR and StandardXHR, thus without rebinding this.type it seems it does not choose the right one.