Events that drive a service worker
A service worker is event-driven: it has no persistent state and wakes only to handle events, then may be terminated. Knowing which events exist, when they fire, and how to extend their lifetime is the core of building reliable offline-capable and push-enabled web apps. This searchable reference lists the lifecycle and functional events with their interfaces and timing.
How it works
Service worker events fall into two groups. Lifecycle events run once per worker version:
self.addEventListener("install", (event) => {
event.waitUntil(caches.open("v1").then((c) => c.addAll(ASSETS)));
});
self.addEventListener("activate", (event) => {
event.waitUntil(clients.claim());
});
Functional events fire repeatedly. The fetch event uses
event.respondWith() to return a response synchronously, while push, sync,
message and the notification events use event.waitUntil() to keep the worker
alive while a promise resolves. Without one of these calls the browser may kill
the worker before your asynchronous work finishes.
Tips and notes
- Precache in
install; purge old caches inactivate. Callclients.claim()to control already-open pages. fetchis the only event that usesrespondWith()— everything else useswaitUntil().- A
pushhandler must show a notification or the browser may flag your origin for silent pushes. syncretries on a backoff if your promise rejects;periodicsyncis throttled by engagement and battery and has limited support.