The Activate Event
You'll learn how the activate event cleans up old resources and finalizes the new service worker's takeover.
What Happens During Activation
After the install event completes successfully, your service worker enters a waiting state. It becomes active when the old service worker is no longer controlling pages. The activate event fires once—and it's your cleanup opportunity.
Think of it like moving into a new apartment: installation was unpacking your boxes, but activation is when you throw out the previous tenant's junk and set up your space properly.
Why Clean Up Old Caches?
When you update your service worker with new cache names (e.g., cache-v2 replacing cache-v1), the old cache still exists. If you don't delete it, users waste storage space and might load stale assets.
Basic Activate Handler
self.addEventListener('activate', event => {
const currentCaches = ['cache-v2'];
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (!currentCaches.includes(cacheName)) {
return caches.delete(cacheName);
}
})
);
})
);
});
This code retrieves all cache names, checks which ones aren't in your "current" list, and deletes the outdated ones. event.waitUntil() ensures the service worker doesn't finish activating until cleanup completes.
Taking Immediate Control
By default, a new service worker won't control pages until they reload. Add clients.claim() inside activate to take control immediately—useful for updates that should apply right away.
Key Takeaway: The activate event is your housekeeping moment—delete old caches and finalize the transition so your new service worker starts fresh and efficient.