DEV Community

Cover image for Sending Web Analytics the better way!!
Abhishek Raj
Abhishek Raj

Posted on

Sending Web Analytics the better way!!

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?

  1. Even if its async, we are using our main thread to send the events.
  2. When the send analytics request is queued and user closes the page, your analytics is lost.
  3. Poor UX due to slow HTTP Requests, if we put analytics send req on document unload event

Read More

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?

  1. It doesn't block your thread.
  2. Browser queues it and takes care to sending the request.
  3. Even after queuing the page is closed, the request will be sent.
  4. It doesn't takes response from server, sends and forgets.
  5. Supported by most of the browsers.

Browser Compatability

Caveats

  1. It only sends POST request.
  2. We can't check if request is received by server.

Connect Me @ Linkedin, Github, Twitter 😃

Top comments (0)