Background Sync and Updates
Update caches and sync when back online.
Background Sync and Updates is a free JavaScript Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the JavaScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Keeping Caches Fresh
An offline-capable app must update gracefully: ship new assets, evict old ones, and retry failed actions when connectivity returns. Service workers provide tools for all three.
Versioned Cache Names
The simplest update mechanism is a versioned cache name. Bumping the version creates a fresh cache, leaving the old one to be cleaned up on activation.
const CACHE = 'app-v2'; // was 'app-v1'
self.addEventListener('install', (e) => {
e.waitUntil(
caches.open(CACHE).then(c => c.addAll(ASSETS))
);
});Cleaning Old Caches
In the activate event, list all cache names and delete any that are not the current version. This frees storage and removes stale assets.
self.addEventListener('activate', (e) => {
e.waitUntil(
caches.keys().then(names =>
Promise.all(
names.filter(n => n !== CACHE)
.map(n => caches.delete(n))
)
)
);
});The Waiting Worker
By default a new worker installs but stays in a waiting state until all pages controlled by the old worker are closed. This avoids version mismatches mid-session.
skipWaiting
self.skipWaiting() tells a waiting worker to activate immediately, taking control without waiting for tabs to close. Call it in install when you want updates to apply right away.
self.addEventListener('install', (event) => {
self.skipWaiting(); // activate as soon as installed
});clients.claim
After activating, self.clients.claim() lets the new worker take control of already-open pages immediately, instead of only controlling future navigations.
self.addEventListener('activate', (event) => {
event.waitUntil(self.clients.claim());
});Detecting Updates From the Page
The page can listen for a new worker via the registration's updatefound event, then prompt the user to reload to get the latest version.
reg.addEventListener('updatefound', () => {
const sw = reg.installing;
sw.addEventListener('statechange', () => {
if (sw.state === 'installed') {
console.log('new version available - reload to update');
}
});
});Background Sync
The Background Sync API lets you defer an action (like sending a form) until the device has connectivity. You register a sync tag, and the browser fires a sync event when online.
// In the page, after queuing data:
reg.sync.register('send-messages')
.then(() => console.log('sync scheduled'));Handling the sync Event
In the service worker, listen for sync and match the tag. Use waitUntil so the browser keeps the worker alive until the retry finishes.
self.addEventListener('sync', (event) => {
if (event.tag === 'send-messages') {
event.waitUntil(sendQueuedMessages());
}
});Queue Then Sync Pattern
A robust offline flow: save the pending action to IndexedDB, register a sync, and in the sync handler read the queue and POST each item, clearing it on success.
async function sendQueuedMessages() {
const items = await readQueueFromIndexedDB();
for (const item of items) {
await fetch('/api/messages', {
method: 'POST',
body: JSON.stringify(item)
});
}
await clearQueue();
}Updates and Sync Recap
Together these features make apps resilient: versioned caches and cleanup keep assets fresh, skipWaiting/clients.claim control rollout timing, and Background Sync reliably completes actions once the user is back online.
Quick Check
Test your understanding of updates and background sync.
Recap
You learned background sync and updates:
- Use versioned cache names and clean old caches on
activate. skipWaitingandclients.claimcontrol update timing.- Detect new versions via
updatefound. - Background Sync defers actions until online via the
syncevent. - Queue in IndexedDB, then flush on sync.
You have completed Service Workers and Offline Caching.
Frequently asked questions
Is the “Background Sync and Updates” lesson free?
Yes — the full text of “Background Sync and Updates” is free to read here on the web, and the JavaScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the JavaScript Academy course, upgrade to CoddyKit PRO.
What will I learn in “Background Sync and Updates”?
Update caches and sync when back online. You practise JavaScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start JavaScript Academy?
No prior experience is required. JavaScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Background Sync and Updates” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this JavaScript Academy lesson?
Yes. Every JavaScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Registering a Service Worker
- The Cache API
- Caching Strategies
- Background Sync and Updates