This content originally appeared on DEV Community and was authored by Abhishek Raj
Most of the big companies have there own analytics rather than using third party services like Google Analytics.
I have seen many of the sites using fetch API or XHRHttpReq for sending analytics event.
What's the issue in using that fetch API/XHR for sending analytics event?
- Even if its async, we are using our main thread to send the events.
- When the send analytics request is queued and user closes the page, your analytics is lost.
- Poor UX due to slow HTTP Requests, if we put analytics send req on document
unload
event
What should we do?
Almost all browser's (except IE) gives an API for this use case.
Beacon API
The Beacon API is used to send an asynchronous and non-blocking request to a web server. The request does not expect a response. Unlike requests made using XMLHttpRequest or the Fetch API, the browser guarantees to initiate beacon requests before the page is unloaded and to run them to completion. - MDN
Why is Beacon API good for sending analytics event?
- It doesn't block your thread.
- Browser queues it and takes care to sending the request.
- Even after queuing the page is closed, the request will be sent.
- It doesn't takes response from server, sends and forgets.
- Supported by most of the browsers.
Caveats
- It only sends POST request.
- We can't check if request is received by server.
Connect Me @ Linkedin, Github, Twitter 😃
This content originally appeared on DEV Community and was authored by Abhishek Raj
Abhishek Raj | Sciencx (2021-12-16T10:23:17+00:00) Sending Web Analytics the better way!!. Retrieved from https://www.scien.cx/2021/12/16/sending-web-analytics-the-better-way/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.