Background Work
Web background work is opportunistic. Design it as a convenience layer over explicit local state, not as a guaranteed job scheduler.
Capability Map
| Capability | Use | Reliability stance |
|---|---|---|
| Background Sync | Retry failed one-shot work when network returns | Useful where supported, not universal |
| Periodic Background Sync | Occasionally refresh data in a service worker | Experimental and browser-controlled |
| Background Fetch | Long-running fetches with browser UI | Limited support, use only after target check |
| Push | Wake service worker for server-sent events | Requires permission, subscription, and push service |
| Foreground retry | Retry when app opens or user taps sync | Required fallback |
Feature-Detect One-Shot Sync
async function requestReplay() {
const registration = await navigator.serviceWorker.ready;
if ('sync' in registration) {
await registration.sync.register('replay-outbox');
return;
}
await replayOutboxInForeground();
}
Worker Handler
self.addEventListener('sync', (event) => {
if (event.tag === 'replay-outbox') {
event.waitUntil(replayOutbox());
}
});
Gotcha: If a write is important, store it first, show pending state, and retry from the foreground. Background Sync may never run on some browsers.