🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Service Workers: Lifecycle, Caching, and Offline Mode

Web FoundationsBrowser APIsđŸŸĸ Free Lesson

Service Workers: Lifecycle, Caching, and Offline Mode

A service worker is a programmable network proxy that sits between your pages and the internet. Once registered, it can serve responses from cache, fulfill requests entirely offline, queue actions for later sync, and receive push notifications — all without the page being open, and all under a lifecycle that is deliberately awkward because the worker outlives the tabs that created it.

That lifecycle is where most service worker bugs live. A worker that caches too aggressively leaves users stuck on stale assets for days. One that caches too little adds a useless layer of indirection. This lesson walks registration, the install and fetch events, the standard caching strategies with their code, and the update mechanics that keep long-lived users current.

Registration and the Secure-Context Requirement

Service workers require HTTPS — or localhost during development. The registration object controls the scope: which paths under the worker's directory the worker may control. A worker at sw.js on the root controls the whole origin; a worker buried in a subdirectory controls only that subtree.

javascript
if ('serviceWorker' in navigator) {
  window.addEventListener('load', async () => {
    try {
      const registration = await navigator.serviceWorker.register('/sw.js', {
        scope: '/',
        updateViaCache: 'none'
      });
      console.log('Service worker registered, scope:', registration.scope);

      registration.addEventListener('updatefound', () => {
        const installing = registration.installing;
        installing.addEventListener('statechange', () => {
          if (installing.state === 'installed' && navigator.serviceWorker.controller) {
            showUpdateBanner(() => {
              installing.postMessage({ type: 'SKIP_WAITING' });
            });
          }
        });
      });
    } catch (error) {
      console.error('Registration failed:', error);
    }
  });
}

The load-event wrapper avoids competing with first paint for network bandwidth, and updateViaCache: 'none' keeps the browser from trusting a cached worker script past its HTTP cache headers — important while you are still learning the update behavior.

The Lifecycle in Three Acts

EventRuns whenTypical job
installFirst registration and every update fetchPrecache the app shell and static assets
activateAfter the new worker takes controlDelete old caches, claim open clients
fetchEvery controlled network requestIntercept, cache, fall back, or pass through

The install event is your chance to open a named cache and add the assets the offline experience needs. If any addAll entry fails, installation fails and the worker never activates — a broken asset URL in your precache list silently blocks the whole feature. The activate event runs once, after every old instance of the worker has released control, which makes it the correct place to delete caches whose version prefix no longer matches. The fetch handler is where the strategy lives, and it must answer every request it claims — including an explicit passthrough for requests you do not want to cache, such as analytics beacons.

Two Strategies That Cover Most Apps

Cache-first suits immutable hashed assets: look in the cache, return on a hit, otherwise fetch and store. Network-first suits HTML and API responses where freshness matters more than speed, with the cache as an offline fallback:

javascript
const CACHE = 'app-shell-v3';
const PRECACHE = ['/', '/styles.css', '/app.js', '/offline.html'];

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE).then((cache) => cache.addAll(PRECACHE))
  );
});

self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then((keys) =>
      Promise.all(keys.filter((key) => key !== CACHE).map((key) => caches.delete(key)))
    ).then(() => self.clients.claim())
  );
});

self.addEventListener('fetch', (event) => {
  const { request } = event;
  if (request.method !== 'GET') return;

  if (request.mode === 'navigate') {
    event.respondWith(
      fetch(request)
        .then((response) => {
          const copy = response.clone();
          caches.open(CACHE).then((cache) => cache.put(request, copy));
          return response;
        })
        .catch(() => caches.match('/offline.html'))
    );
    return;
  }

  event.respondWith(
    caches.match(request).then((cached) => {
      if (cached) return cached;
      return fetch(request).then((response) => {
        if (response.ok) {
          const copy = response.clone();
          caches.open(CACHE).then((cache) => cache.put(request, copy));
        }
        return response;
      });
    })
  );
});

Notice the response clone before put: a Response body can only be read once, and caching a consumed stream yields an empty entry. Notice also the offline page as the navigation fallback — without it, an offline user sees the browser's own error page instead of anything of yours.

A third strategy, stale-while-revalidate, serves the cached copy instantly and refreshes it in the background. It is the right default for icon sets and font files: the user never waits, and the cache self-heals. The cost is that the first visit after a deploy can still show one old asset; hashed filenames sidestep the problem entirely by making every deploy a new cache key.

Cache Naming Is Your Versioning System

The cache name encodes the deploy version. When PRECACHE or the build's asset hashes change, bump the name: the new worker installs with a fresh cache, activates, deletes everything that is not the new name, and only then starts serving. Because the old cache remains readable until activation, open tabs keep working against the version they loaded with — no mixed-asset half-states during the transition.

The Update Trap, and How to Escape It

The scenario every long-lived PWA eventually hits: a user keeps one tab open for a week, the service worker updates twice in that time, and the page's cached HTML references asset bundles that the activate step has already deleted. The fix has two halves. First, precache only versioned assets that new HTML will reference, and serve HTML network-first so a fresh load always gets fresh markup. Second, when the user clicks the update banner, post skip-waiting to the waiting worker and reload the page once — clients.claim plus a controlled reload is the only way to guarantee the new assets and the new HTML arrive together.

âš ī¸Never cache non-idempotent responses

Caching POST responses, personalized API GETs, or authenticated JSON is how service workers leak one user's data to another. Scope your fetch handler to static assets and navigations, check response.ok and content-type before storing, and leave anything behind a session cookie uncached by default.

Push, Sync, and What Else the Proxy Can Do

The same worker doubles as a push endpoint: a push event wakes the worker even with no tabs open, and showNotification presents the result through the Notifications API, subject to permission. Background Sync queues failed POSTs and retries them when connectivity returns — useful for note-taking apps on flaky mobile networks, and a progressive enhancement because Safari has not shipped it. Both features ride on the same registration and the same lifecycle you have already built; they are additional events on an already-installed worker, not separate infrastructure.

Debugging the Invisible Layer

Service workers are hard to observe, so learn the devtools panel early. The Application tab shows the worker state, every cache and its entries, and a hard-reset button for when you have locked yourself out of your own app during development. Unregister the worker and clear storage after major strategy changes; a worker controlling a page from an old deploy will keep serving old responses no matter how you edit the network code. In production, log strategy decisions — cache hit, network, fallback — through postMessage to a visible debug overlay while you gain confidence, then remove the instrumentation once the hit rates look right in real traffic.

Navigation preload, where supported, is a quiet performance win: the browser starts the network request for a navigation in parallel with service worker startup, and the fetch handler responds with the preloaded response instead of waiting for its own fetch call. It removes the startup latency that the network-first strategy would otherwise add on repeat visits, at the cost of one extra branch in the handler. Feature-detect before enabling, and skip the extra complexity if your traffic is dominated by asset requests rather than navigations.

Common Mistakes

Forgetting to clone the Response before caching it

Fix: response.clone() before cache.put — a body can only be read once.

Caching personalized or authenticated API responses

Fix: Limit interception to static assets and navigations; check content-type before storing.

Never bumping the cache name between deploys

Fix: Version the cache string with every release so activate can purge stale assets.

Shipping without an offline fallback page

Fix: Precache a small offline.html and serve it when navigation fetches fail.

Calling skip-waiting unconditionally on install

Fix: Let the user trigger updates from a banner, then reload once so HTML and assets swap together.

Key Takeaways

  • A service worker is a network proxy with its own lifecycle: install precaches, activate cleans up, fetch strategizes.
  • Registration requires HTTPS, and the worker's directory defines its scope.
  • Cache-first suits immutable assets; network-first suits HTML; stale-while-revalidate balances both.
  • Version your cache names with every deploy and delete old ones in activate.
  • Clone responses before caching, never cache authenticated JSON, and always ship an offline fallback.
  • Update flows need skip-waiting plus a controlled reload to avoid mixing old HTML with deleted assets.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement