PWA Guide
Service Worker cheatsheet
A short practical reference: lifecycle, fetch handling, and cache strategies that work in real Chrome and Safari projects.
All materials
1. What it is
A Service Worker is a script that sits between your page and the network. It can cache files, answer offline, and handle background tasks like push.
Register once from your page:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js');
}
2. Lifecycle (simple mental model)
| Event | When | What to do |
install | SW is downloaded first time / updated | Precache app shell (HTML/CSS/JS/icons) |
activate | Old SW is gone, new one takes control | Delete old caches |
fetch | Page or worker requests a URL | Return cache, network, or both |
message | Page talks to SW | Trigger skipWaiting / custom commands |
3. Minimal SW skeleton
const CACHE = 'app-v1';
const PRECACHE = ['/', '/offline.html', '/static/app.css', '/static/app.js'];
self.addEventListener('install', (event) => {
event.waitUntil(caches.open(CACHE).then((c) => c.addAll(PRECACHE)));
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
event.waitUntil((async () => {
const keys = await caches.keys();
await Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)));
await self.clients.claim();
})());
});
self.addEventListener('fetch', (event) => {
if (event.request.method !== 'GET') return;
event.respondWith((async () => {
const cached = await caches.match(event.request);
if (cached) return cached;
try {
const fresh = await fetch(event.request);
const cache = await caches.open(CACHE);
cache.put(event.request, fresh.clone());
return fresh;
} catch {
return caches.match('/offline.html');
}
})());
});
4. Cache strategies
| Strategy | Best for | Idea |
| Cache First | CSS, JS, fonts, icons | Use cache, network only on miss |
| Network First | HTML, API JSON | Try network, fall back to cache |
| Stale While Revalidate | Semi-fresh content | Return cache now, update in background |
| Network Only | Payments, auth | Never trust cache |
5. Chrome vs Safari
| Topic | Chrome / Chromium | Safari / iOS |
| Basic SW + Cache API | Strong support | Supported, with storage limits |
| Background sync | Available | Limited / often unavailable |
| Storage eviction | Usually stable for installed PWAs | Can clear data more aggressively |
| HTTPS | Required (localhost ok) | Required |
6. Common mistakes
- Caching POST/API auth responses by accident.
- Never bumping cache version - users stay on old JS forever.
- Precaching huge image sets on install - install becomes slow.
- Forgetting an offline fallback for navigations.