Analytics and diagnostics code are very useful, but they always result in extra time. The Beacon API comes to our rescue!
The Problem
The browser normally ignores asynchronous XMLHttpRequests made in an unload handler. Common workarounds:
- Use synchronous XMLHttpRequest
- Delay the unload using an image element
- Create a no-op loop for several seconds
All are poor coding patterns.
The Solution: Beacon API
The Beacon specification defines an interface for asynchronously transferring small HTTP data from the User Agent to a web server.
navigator.sendBeacon(url, data)
// Returns true on success, false otherwise
### Before (XMLHttpRequest)
javascript
window.addEventListener('unload', logData, false);
function logData() {
var client = new XMLHttpRequest();
client.open("POST", "/log", false); // sync xhr
client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
client.send(analyticsData);
}
### After (Beacon API)
javascript
window.addEventListener('unload', logData, false);
function logData() {
navigator.sendBeacon("/log", analyticsData);
}
What People Say
“It’s like UDP over TCP but for webpages.” — @FakeAlexRussell
“A ‘fire-and-forget’ XMLHttpRequest replacement for faster page unloads (& next page loads)” — @richtibbett
About Hemanth HM
Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.