Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest.onreadystatechange vs. addEventListener

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.

like image 798
Jack Steam Avatar asked Jan 20 '16 16:01

Jack Steam


2 Answers

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.

like image 134
Spencer Easton Avatar answered Oct 16 '22 16:10

Spencer Easton


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.

like image 30
minj Avatar answered Oct 16 '22 16:10

minj