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

CapabilityUseReliability stance
Background SyncRetry failed one-shot work when network returnsUseful where supported, not universal
Periodic Background SyncOccasionally refresh data in a service workerExperimental and browser-controlled
Background FetchLong-running fetches with browser UILimited support, use only after target check
PushWake service worker for server-sent eventsRequires permission, subscription, and push service
Foreground retryRetry when app opens or user taps syncRequired 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.