A service worker sits between the page and the network, able to intercept every request. What it does with that power comes down to a caching strategy, and picking the right one per resource type matters more than the boilerplate code around it.

Cache-first for static assets

self.addEventListener('fetch', e => {
  e.respondWith(caches.match(e.request).then(r => r || fetch(e.request)));
});

Good for CSS, fonts, and logo images - things that rarely change and benefit from instant, offline-capable loading.

Network-first for content that updates often

self.addEventListener('fetch', e => {
  e.respondWith(
    fetch(e.request).catch(() => caches.match(e.request))
  );
});

This falls back to cache only when the network genuinely fails, keeping content fresh whenever a connection is available and still usable when it isn't.

Most real sites end up mixing both strategies by resource type, which is exactly what the Cache API's flexibility is built for.

A programmable network proxy running in the browser

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request).then((cached) => cached || fetch(event.request))
  );
});

That's the core idea: a service worker intercepts every network request the page makes and decides how to respond - from cache, from the network, or some combination - which is what makes true offline support and instant repeat-visit loads possible.

Choosing a caching strategy per resource type

Cache-first suits static assets that rarely change (fonts, logos); network-first with a cache fallback suits content that should be fresh when possible but usable offline when not (an API response, an article page). Using the same strategy for everything is the most common service-worker mistake - a cache-first strategy applied to an API endpoint will happily serve stale data indefinitely unless the cache is explicitly invalidated on update.