Water valley guide: 22 levels wiring a SW handler and cache layers (memory LRU, Cache API, IDB). Real fault injection and hit-rate metrics, not cache theory.
A service worker is a script the browser installs between the page and the network. Every time the page asks for something, the browser hands it a fetch event; the service worker may answer it itself with event.respondWith(...), for example from Cache Storage (caches.open, cache.match, cache.put). If it stays silent, the request goes on to the network as if there were no service worker. Here Mr. Sukri is the service worker, the jars at his stand are Cache Storage, and Sumur Kepuh is the network.
A service worker lives through three stages: install (set up, the right moment to fill a cache), activate (taking over, the right moment to clear old ones), then fetch for every request. event.waitUntil(promise) makes the browser wait for that promise before the stage counts as done. self.skipWaiting() and self.clients.claim() let a new version take over at once without waiting for the old tabs to close.
The browser has two places to keep things. The HTTP cache is ruled by the server through the Cache-Control header (max-age=3600, no-cache, no-store), and the browser decides when to use it. Cache Storage is ruled by your code: what you put stays until you delete it, whatever its headers say.
The reverse of the jar first: the network first. Try fetch; if it works, give it and keep a copy; if fetch is refused (no network), take it from the cache. It suits data that must be the latest but still has to be there offline.
Stale-while-revalidate: give what is in the cache right away, then fetch a new version behind it for the next request. event.waitUntil(promise) keeps the service worker alive until that fetch behind it is done.
When a service worker's code changes, the browser installs the new version beside the old one. The new version's install fills its cache; activate is when the old version has let go, the place to clear caches no longer used with caches.keys() and caches.delete(name).