Send analytics with navigator.sendBeacon() without blocking the page

A common problem when sending statistical (analytics) data to the server from the frontend is that when using AJAX, you often end up blocking the page load. Fortunately, there’s a native solution.

The navigator.sendBeacon() method accepts two parameters:

  1. The URL (relative or absolute) to send the request to.
  2. The data to send, as a string, object, FormData, Blob, ArrayBuffer, TypedArray, DataView, or an instance of URLSearchParams.

This method does not immediately perform the POST request to the server; instead, it queues it for the browser to execute later. This is the key difference from AJAX, which sends the request immediately.

Suppose we want to send the server the identifier of the browser used by the client by reading the userAgent string. We can write:

function sendStats() {
    navigator.sendBeacon('/stats', navigator.userAgent);
}

We can run this function at a specific moment in a web page’s lifecycle—for example, when the user has finished interacting with the page.

document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'hidden') {
    sendStats();
  }
});

For this kind of scenario, the unload, beforeunload, and pagehide events tend to be inefficient and unreliable, especially on mobile devices.

Conclusion

The sendBeacon() method is designed specifically to send statistical data to the server without blocking the page as AJAX might. Being a native method, it’s particularly well-suited as a replacement for AJAX in this context.

Back to top