d--b d--b - 21 days ago 8
Javascript Question

Why does the load event get called with ProgressEvent object?

I am trying to load binary data asynchronously in the browser:

var req = new XMLHttpRequest();
req.open("GET", "test.bin");
req.responseType = "arraybuffer";
req.addEventListener("load", function(res) {
var arrayBuffer = res.response; // Note: not oReq.responseText
...


but the load event that gets triggered has a
res
object that is a
ProgressEvent
.

Is that normal? I'm using chrome and reading the docs on MDN:
https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Why are the docs wrong? This should skip the progress events, no?

Answer

The docs aren't wrong and neither are you. The response object is a ProgressEvent from the load event. In order to get access to the response you need to point back to the original request (req) in your case.

var req = new XMLHttpRequest();
req.open("GET", "test.bin");
req.responseType = "arraybuffer";
req.addEventListener('load', function(res) {
  var arrayBuffer = req.response;
});

The ProgressEvent also has access to the source via currentTarget. For example:

req.addEventListener("load", function(res) {
  var arrayBuffer = res.currentTarget.response
});

And here is a fiddle: https://jsfiddle.net/08zm9urL/1/

Also Note:

You cannot access responseText when the responseType is arraybuffer. It must be either an empty string or text.

If responseType is set to anything other than the empty string or "text", accessing responseText will throw InvalidStateError exception.

From https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText

Comments