Send analytics late with fetchLater
Queue a small analytics snapshot while the page is active, replace it on each click, and fall back to a beacon.
You count clicks for a page and send the total in a pagehide handler. If the browser never runs that handler, the total never reaches the queue. With fetchLater(), you can give the browser a request while the page is active.
Queue the latest count
Chrome shipped deferred fetch in version 135. The browser can start a queued request when the document is destroyed or enters the back/forward cache. You can also schedule activation with activateAfter, in milliseconds. The returned object's activated flag tracks activation, and the browser discards the response.
Serve the page over HTTPS or localhost with a same-origin POST /collect endpoint. Add a button with id count, then place this script after it.
const session = crypto.randomUUID()
let clicks = 0
let pending
let useBeacon = typeof window.fetchLater !== 'function'
function queueCount() {
if (useBeacon) return
pending?.abort()
const controller = new AbortController()
try {
window.fetchLater('/collect', {
method: 'POST',
body: JSON.stringify({ session, clicks }),
signal: controller.signal,
})
pending = controller
} catch (error) {
if (error.name !== 'QuotaExceededError') throw error
pending = undefined
useBeacon = true
}
}
document.querySelector('#count').addEventListener('click', () => {
clicks += 1
queueCount()
})
document.addEventListener('visibilitychange', () => {
if (useBeacon && clicks > 0 && document.visibilityState === 'hidden') {
navigator.sendBeacon('/collect', JSON.stringify({ session, clicks }))
}
})In a browser with deferred fetch, three clicks followed by a tab close can send one snapshot with clicks: 3.
diagram
Pending request across three clicks
Aborting cancels a pending request. A request the browser has started may still reach the server. Store the greatest count seen for a given session ID so duplicate or out-of-order snapshots leave the right total. Parse the incoming body as text containing JSON in this example.
Leave room for the fallback
Keep the payload small. The deferred fetch quota also counts other pending requests, and permissions policy can reduce the quota to zero. If the browser throws QuotaExceededError, the example switches to a beacon.
The fallback asks sendBeacon() to queue the snapshot when the document becomes hidden. A return value of false means the browser could not queue it. A page can become hidden more than once, which is another reason to merge counts by session.
To exercise deferred fetch, open the page on localhost, click three times, and close the tab. To exercise the fallback in a browser without fetchLater(), click three times and navigate away in the same tab so the page becomes hidden. Check the collector’s log for a count of three in either case.