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)

EventWhenWhat to do
installSW is downloaded first time / updatedPrecache app shell (HTML/CSS/JS/icons)
activateOld SW is gone, new one takes controlDelete old caches
fetchPage or worker requests a URLReturn cache, network, or both
messagePage talks to SWTrigger 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

StrategyBest forIdea
Cache FirstCSS, JS, fonts, iconsUse cache, network only on miss
Network FirstHTML, API JSONTry network, fall back to cache
Stale While RevalidateSemi-fresh contentReturn cache now, update in background
Network OnlyPayments, authNever trust cache

5. Chrome vs Safari

TopicChrome / ChromiumSafari / iOS
Basic SW + Cache APIStrong supportSupported, with storage limits
Background syncAvailableLimited / often unavailable
Storage evictionUsually stable for installed PWAsCan clear data more aggressively
HTTPSRequired (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.