Service Worker Lifecycle
The service worker lifecycle is the sequence of states a service worker script passes through from initial registration to becoming the active controller of a web page's network requests.
The service worker lifecycle is the sequence of states a service worker script passes through from initial registration to becoming the active controller of a web page's network requests.
A service worker is a JavaScript file that runs in a separate worker thread with no DOM access and acts as a network proxy between the browser and the server. Its primary uses are enabling offline functionality, caching assets for instant repeat loads, and push notifications. The lifecycle is deliberately cautious — a new service worker does not immediately replace the previous one to avoid breaking pages currently open in the browser.
The lifecycle begins with registration via navigator.serviceWorker.register('/sw.js'). The browser downloads the script and moves it to the installing state, where the install event fires. This is the critical caching step: the install handler typically calls caches.open() and pre-caches the app shell (HTML, CSS, JS files) using the Cache Storage API. If any file in the pre-cache list fails to download, installation fails and the service worker returns to redundant state.
After a successful install, the service worker enters the waiting (installed) state. It stays here as long as any open page in the browser is still controlled by the *previous* service worker. The new version takes over only when all such pages are closed or when skipWaiting() is called explicitly. This prevents mismatched asset versions between the old service worker's cached responses and the new page's expectations.
Once no other service worker controls any open page, the new worker activates. The activate event is the correct place to clean up old caches from the previous version. After activation, the service worker enters the active state and intercepts all fetch events from controlled pages. See Offline First App Flow for how an active service worker handles cache-vs-network decisions per request.