A service worker sees every request its controlled pages make: the navigations into its scope and every subresource request, cross-origin ones included. Each fires a fetch event with event.request. Calling event.respondWith(promise) during dispatch makes that promise's Response the answer; not calling it lets the request go to the network as usual.
The Cache API (caches.open(name), then match, put, add, addAll, delete, keys) is where responses usually come from. It's a store of request/response pairs that only your code reads and writes, unrelated to the HTTP cache that fetch's cache option controls. Entries are keyed by URL, query included, and only GET requests can be stored. They stay until deleted or until the origin is evicted, and count against the origin's storage quota.
Strategies, by what the resource needs:
- Cache-first: return the cached copy; go to the network only on a miss. For versioned static files (
app.3f9a.js) that never change at the same URL. - Network-first: try the network, update the cache, fall back to the cache when offline. For HTML and data that must be current when possible.
- Stale-while-revalidate: answer from the cache immediately, refresh the cache in the background. The next visit sees the update. For avatars and data that may lag one load behind.
- Cache-only / network-only: for precached assets, and for requests that must never be cached, like analytics or
POST.
Navigation preload. A navigation that hits a stopped service worker waits for it to boot before the request even starts. registration.navigationPreload.enable() makes the browser send the navigation request in parallel, with a Service-Worker-Navigation-Preload header; the worker uses it through event.preloadResponse.
Workbox packages these strategies, but they're a few lines each.