Lesson 4 / 29
Service Worker lifecycle
Deep dive into install, activate, and fetch events in the service worker lifecycle.
Lifecycle events
Service workers emit three key events: install (first load), activate (old version cleanup), and fetch (network interception). Each event is your chance to cache assets and control behavior.
Handle lifecycle events
This service worker caches assets on install and cleans up old caches on activate.
const CACHE_NAME = 'v1';
const urls = ['/', '/index.html', '/styles.css', '/app.js'];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME).then(cache => cache.addAll(urls))
);
});
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(keys =>
Promise.all(keys.map(key => key !== CACHE_NAME && caches.delete(key)))
)
);
});
Output:
Assets cached on install, old cache versions removed on activate.
A common trap
Always use event.waitUntil() in install and activate events to ensure operations complete before the event ends.
Lifecycle event handling patterns
Practice handling install and activate events in various scenarios.