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.
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 theXMLHttpRequest
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 standardaddEventListener
APIs in addition to settingon*
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With