Describe the Service Worker lifecycle and cache versioning

Tests your grasp of the Service Worker lifecycle and cache versioning. A strong answer sequences register, install, activate, and fetch; notes install precaches assets while activate purges old caches and finalizes takeover.
WHAT THIS TESTS: This question probes whether you understand the event-driven lifecycle of a Service Worker as a proxy layer, not just the API signatures. Interviewers want to see that you know why activation is deferred, how cache versioning avoids storage bloat and corruption, and how the worker transitions from installation to controlling pages.
A GOOD ANSWER COVERS: First, the four main phases in order. Registration via navigator.serviceWorker.register fetches the script. Second, the install event fires first and is used to precache core static assets into CacheStorage so the app shell is available offline. Third, the activate event is critical because the new worker will not take over until all pages controlled by the previous worker have closed; during activation you delete old caches that do not match the current cache name to prevent stale assets and quota exhaustion. Fourth, the fetch event intercepts network requests after activation and allows cache-first, network-first, or stale-while-revalidate strategies. A senior candidate also mentions skipWaiting to force immediate activation and clients.claim to take control of unclaimed clients.
COMMON WRONG ANSWERS: Saying that a newly installed worker immediately controls all open tabs without mentioning the waiting phase. Claiming that install and activate are synchronous or happen at the same time. Stating that Service Workers have DOM access or run on the main thread. Failing to mention cache cleanup during activate, which leads to unbounded storage growth and version mismatches between HTML and cached assets.
LIKELY FOLLOW-UPS: How does skipWaiting differ from clients.claim? What cache strategy would you use for API responses versus static assets? How do you handle a failed install or a partial cache? How does the browser decide when to check for an updated service worker? What is navigation preload and when would you use it?
ONE CONCRETE EXAMPLE: Suppose your app uses cache-v1 for install. You update the shell and register cache-v2. During the new install event you populate cache-v2 with index.html and bundle.js. The new worker then waits because a user still has a tab open with the old worker. Once that tab closes, activate fires; inside it you call caches.keys and delete any cache whose name is not cache-v2. Now fetch events serve from cache-v2, ensuring the HTML and JS versions never mismatch.
Source: developer.mozilla.org
Read the original → developer.mozilla.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.