A service worker decides, for every request, where the answer comes from. There are five classic strategies. Most apps use three of them for different kinds of request.
1. Cache first (cache falling back to network)
Look in the cache; if missing, fetch and store.
async function cacheFirst(request, cacheName) {
const cache = await caches.open(cacheName);
const hit = await cache.match(request);
if (hit) return hit;
const res = await fetch(request);
if (res.ok) cache.put(request, res.clone());
return res;
}
Use for: files with a version or hash in the name (app.3f9a1c.js, style.css?v=12), fonts, icons. They never change at the same URL, so the cache is always right.
2. Network first (network falling back to cache)
Try the network; store a copy; if it fails, use the cached copy.
async function networkFirst(request, cacheName, timeoutMs = 4000) {
const cache = await caches.open(cacheName);
try {
const res = await Promise.race([
fetch(request),
new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), timeoutMs)),
]);
if (res.ok) cache.put(request, res.clone());
return res;
} catch {
return (await cache.match(request)) || caches.match('/offline.html');
}
}
Use for: HTML pages and API data that must be fresh when online. The timeout matters: on a bad connection ("lie-fi"), waiting 30 seconds for the network is worse than showing a slightly older page.
3. Stale-while-revalidate
Answer from the cache straight away, and update the cache in the background for next time.
async function staleWhileRevalidate(event, cacheName) {
const cache = await caches.open(cacheName);
const hit = await cache.match(event.request);
const update = fetch(event.request).then((res) => { if (res.ok) cache.put(event.request, res.clone()); return res; });
if (hit) { event.waitUntil(update.catch(() => {})); return hit; }
return update;
}
Use for: things that change but where one visit out of date is fine: avatars, non-hashed CSS, Google Fonts stylesheets, product lists, configuration.
4. Network only
Do not cache. Use for: payments, logins, analytics, admin, anything personal or non-GET. (Simply not calling respondWith does this.)
5. Cache only
Only from cache. Use for: the precached app shell, after install.
A typical setup
| Request | Strategy | Cache limit |
|---|---|---|
| HTML navigations | Network first, 3 to 4 s timeout, offline page fallback | 50 to 100 pages |
| Hashed JS and CSS | Cache first | Version-named cache |
| Images | Cache first | 60 entries, 30 days |
| Fonts | Stale-while-revalidate (CSS), cache first (files) | 30 entries, 1 year |
| JSON API (public) | Network first or stale-while-revalidate | 50 entries, 1 day |
| JSON API (private), POST, auth | Network only | none |
PWA.live uses exactly this pattern: open DevTools > Application > Cache storage to see it.
Pitfalls
- Opaque responses from other origins (
mode: 'no-cors') have status 0 and count as several MB of quota each in Chrome. Only cache them when you must. - Never cache personalised HTML under a shared URL.
Varyheaders can makecache.matchmiss;ignoreVary: truehelps.- Query strings make different cache keys; use
ignoreSearch: truewhen the query does not change the content.
Pick a strategy interactively with the caching strategy picker, or generate a full worker with the service worker generator.
Compatibilidade de navegadores
| Recurso | Chrome / Edge desktop | Chrome Android | Safari iOS / iPadOS | Safari macOS | Firefox desktop | Firefox Android | Samsung Internet |
|---|---|---|---|---|---|---|---|
| Service workers | Chrome / Edge desktop: Sim | Chrome Android: Sim | Safari iOS / iPadOS: Sim | Safari macOS: Sim | Firefox desktop: Sim | Firefox Android: Sim | Samsung Internet: Sim |
| Cache API | Chrome / Edge desktop: Sim | Chrome Android: Sim | Safari iOS / iPadOS: Sim | Safari macOS: Sim | Firefox desktop: Sim | Firefox Android: Sim | Samsung Internet: Sim |