Lesson 12 / 29
Update strategies
Implement strategies to update service workers and cached content without breaking user experience.
Update patterns
When service workers or cache changes, you need strategies to safely update without breaking ongoing operations. Patterns include checking for updates, skipping waiting, and notifying users.
Detect and update service worker
Check for updates periodically and notify users when a new version is available.
navigator.serviceWorker.getRegistration().then(reg => {
setInterval(() => {
reg.update(); // Check for updates
}, 60000); // Every minute
});
let newWorker;
navigator.serviceWorker.addEventListener('controllerchange', () => {
console.log('New service worker controlling the page');
// Notify user to refresh
});
navigator.serviceWorker.onmessage = event => {
if (event.data.type === 'SKIP_WAITING') {
newWorker?.postMessage({ type: 'CLIENTS_CLAIM' });
}
};
Output:
App checks for service worker updates and notifies users of new versions.
A common trap
Do not force immediate updates without notifying users. Let users decide when to refresh their app.