8

Reading up on XMLHttpRequest for use in a Google Chrome Extension, and I've run into a question.

MDN specifies using XMLHttpRequest.addEventListener, while Google uses XMLHttpRequest.onreadystatechange in their example.

Is there a preference between these two methods when making a GET request to Google Apps Script? I'm new to asynchronous Javascript, prior to this I've just been working in GAS.

Jack Steam
  • 4,500
  • 1
  • 24
  • 39

3 Answers3

10

The preference would be browser compatibility. From the XMLHttpRequest API docs on MSN.

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#Properties

onreadystatechange as a property of the XMLHttpRequest instance is supported in all browsers.

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#Events

More recent browsers, including Firefox, also support listening to the XMLHttpRequest events via standard addEventListener APIs in addition to setting on* properties to a handler function.

As Apps Script Web Apps will soon only support modern browsers (as native and emulated modes are depreciated) you can use either.

Xan
  • 74,770
  • 16
  • 179
  • 206
Spencer Easton
  • 5,642
  • 1
  • 16
  • 25
4

onreadystatechange fires too much and you probably don't need to listen to it. Use loadend (all cases including failure/abort), load (success), error, abort events instead.

See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest for more information.

minj
  • 2,080
  • 12
  • 10
  • You make a point. `onreadystatechange` fires on every state change, but `addEventListener` listens for a specific event (`loadend`, `load`, `error`, `abort`). – Jack Steam Jan 22 '16 at 16:46
2

Also, if you have control of browser type/version, you can do a polyfill using the object passed to onreadystatechange funcion:

var oReq = new XMLHttpRequest();
// This part for modern browsers
oReq.addEventListener("progress", updateProgress, false);
oReq.addEventListener("load", transferComplete, false);
oReq.addEventListener("error", transferFailed, false);
oReq.addEventListener("abort", transferCanceled, false);
// This part for old ones
oReq.onreadystatechange = functionSwitch;

Where functionSwitch will call the right function (will choose between updateProgress, transferComplete, ...) so avoiding double code.

I have seen people using Windows XP yet and probably ANY addEventListener won't work. Have a look: addEventListener Compatibility. I didn't find a specific list of xmlhttprequest events via addEventListener.

Gustavo
  • 1,673
  • 4
  • 24
  • 39