Beacons are a new API that is being experimentally introduced by browser vendors that will allow an XHR call to be made to a server when a webpage unloads without blocking the thread in order to create a better user experience. Quoting the W3C Beacon Specification.

"analytics and diagnostics code will typically make a synchronous XMLHttpRequest in an unload or beforeunload handler to submit the data. The synchronous XMLHttpRequest forces the User Agent to delay unloading the document, and makes the next navigation appear to be slower. There is nothing the next page can do to avoid this perception of poor page load performance."

This specification will prevent developers from having to use tricks and hacks to bend the rules of the browser, creating a better experience for everyone.

Example

Trigger a call to an analytics API as the browser page is unloaded.

window.addEventListener("unload", function() {
    navigator.sendBeacon("/api/analytics", data);
}, false);

The spec details that the data payload must be either an ArrayBufferView, Blob, DOMString or FormData. This means sending a JavaScript object will not work, as "toString" will be called on it.

Beacon with raw JS object

To send a plain JavaScript object, use the JSON library to encode the data before sending it.

Beacon with JSON string object

Try it Out

To enable beacons in Chrome, download the Chrome Canary development version and navigate to "chrome://flags/#enable-experimental-web-platform-features".

Click the "Enable" link and hit "Relaunch Now" to save changes. Once chrome restarts, the navigator.sendBeacon API will be available for use.

An implementation of beacons is in progress and will also arrive shortly in the FireFox Nightly browser.