Background Sync API Basics
What you'll learn: How to register and handle Background Sync events in your service worker to retry failed network operations.
Understanding the Background Sync API
The Background Sync API lets you defer actions until the user has stable connectivity. When a network request fails (say, posting a form while offline), you can register a "sync" event. Once the browser detects a connection, it wakes up your service worker to retry that operation—even if the user has closed your app.
Think of it like leaving a sticky note on your fridge: "Mail this package when you get a chance." The browser is your responsible roommate who actually mails it when conditions are right.
Registering a Sync Event
Inside your application code (not the service worker), you register a sync event through the service worker registration:
// In your main app code
navigator.serviceWorker.ready.then(registration => {
return registration.sync.register('post-data');
});
The string 'post-data' is a tag—a unique identifier for this sync event. You can use any name that describes the action.
Listening in the Service Worker
In your service worker file, listen for the sync event:
// In your service worker
self.addEventListener('sync', event => {
if (event.tag === 'post-data') {
event.waitUntil(
// Retry your network operation here
fetch('/api/submit', { /* options */ })
);
}
});
The event.tag tells you which sync task triggered. Use event.waitUntil() to keep the service worker alive while your async operation completes—just like you did in install and activate events.
Key Takeaway: Background Sync uses registration.sync.register() in your app code and a sync event listener in your service worker to automatically retry failed operations when connectivity returns.