jehna / ga-lite

Small, cacheable and open version of Google Analytics JS client
MIT License
639 stars 55 forks source link

XMLHttpRequest on main thread is deprecated #71

Open Jos512 opened 5 years ago

Jos512 commented 5 years ago

If I perform a Google mobile friendly test on a website that uses ga-lite, I get the following error message:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/

Here's an example of such a mobile friendliness report.

The problem looks to be caused by this line.

jehna commented 5 years ago

Hmm. This tracks down to the very first commit:

https://github.com/jehna/ga-lite/blob/719d3c7171395fa2ee0aec5468625d1ecd07f7ca/src/ga-lite.js#L21-L22

Back then ga-lite had functionality of sending the pageviews on window.onunload, and since Internet Explorer doesn't support navigator.sendBeacon, there was a fallback to use XMLHttpRequest. The gist here is that IE needed to use synchronous requests to guarantee taht those requests were finished on the unload event.

This means we can safely remove the synchronous flag from the XMLHttpRequest call.

jehna commented 5 years ago

Source and further explanation for the synchronous flag:

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