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.
Top comments (0)