← Lessons

quiz vs the machine

Gold1420

Frontend

Service Worker Caching Strategies

A service worker intercepts requests and applies a strategy chosen per resource type.

5 min read · core · beat Gold to climb

A programmable cache

A service worker is a background script that intercepts network requests and decides how to respond. It enables offline support and fine grained caching using the cache storage API.

The common strategies

Each request type suits a different balance of speed and freshness.

  • Cache first: serve from cache, fall back to network. Best for hashed static assets.
  • Network first: try the network, fall back to cache on failure. Best for fresh data like an API.
  • Stale while revalidate: serve the cached copy immediately, then update the cache in the background for next time.
  • Network only and cache only: the simple extremes.

Lifecycle care

A worker installs, activates, then controls pages. You must version the cache name and clean old caches on activate, or users get stuck on stale assets.

  • Precache the app shell during install.
  • Use stale while revalidate for assets that can lag one visit.
  • Never cache responses with errors or partial content.

The strategy is chosen in the fetch event handler based on the request URL or destination.

Key idea

Pick a strategy per resource: cache first for static assets, network first for fresh data, and stale while revalidate for the speed and freshness blend.

Check yourself

Answer to earn rating on the learn ladder.

1. Which strategy serves the cache instantly then updates it in the background?

2. Which strategy best fits fresh API data?

3. Why version the cache name and clean old caches on activate?