Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 37 ยท Caching Strategies

Precaching and Cache Versioning

Learn precaching for PWAs: cache the app shell at install time, version caches and files with hashes, clean up on activate, and let Workbox generate the manifest.

The strategies of the previous lessons decide what to do when a request happens (runtime caching). Precaching is the other half: putting files into the cache ahead of time, during the service worker install event, so the app works offline from the very first reload. Precaching is what guarantees that the app shell exists before the user goes offline. Versioning is what keeps that shell correct when you release a new build.

Precaching in plain code

JavaScript
const VERSION = 'v7';
const SHELL_CACHE = `shell-${VERSION}`;
const SHELL_FILES = [
  '/',
  '/index.html',
  '/app.js',
  '/styles.css',
  '/icons/icon-192.png',
  '/offline.html',
];

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

self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then((names) =>
      Promise.all(
        names
          .filter((n) => n.startsWith('shell-') && n !== SHELL_CACHE)
          .map((n) => caches.delete(n))
      )
    )
  );
});

self.addEventListener('fetch', (event) => {
  if (event.request.method !== 'GET') return;
  event.respondWith(
    caches.match(event.request, { ignoreSearch: true }).then((hit) => hit || fetch(event.request))
  );
});

This is a complete, correct small worker: install fills a versioned cache, activate removes older ones, fetch answers shell files from it. Bump VERSION on every release and the whole cycle happens automatically through the update flow you learned before.

Three things to improve at scale.

1. Do not re-download unchanged files

With VERSION bumped, every file is downloaded again even when only one changed. For large apps, that wastes bandwidth. The solution is revisioned entries: record a hash for each file, and download only files whose hash changed since the last version.

2. Do not cache stale copies from the HTTP cache

cache.addAll(urls) honors the browser's HTTP cache. If /app.js was fetched five minutes ago with max-age=3600, the worker may store that (old) copy again. Fix: use content-hashed file names (the HTTP cache cannot be stale for a name that changed) or fetch with new Request(url, { cache: 'reload' }).

JavaScript
await cache.addAll(SHELL_FILES.map((url) => new Request(url, { cache: 'reload' })));

3. Generate the file list

Hand-written lists rot. Build tools produce them: Workbox's generateSW / injectManifest, Vite's PWA plugin, Angular's ngsw, Next.js PWA plugins. They scan the build output, compute a hash (revision) for each file and inject the list into your worker.

Revisions: a runnable diff

This stand-in computes which files a new build must download, which can be reused and which must be deleted, using a simple hash of the content (a real tool uses MD5 or SHA digests of the file bytes).

JS Stand-in: precache only what changed

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Two files were reused. In a real app with hundreds of files, that is a large saving on every release.

Workbox in a nutshell

Workbox is Google's open-source library that implements all of the above: precaching with revisions, routing, strategies, expiration, background sync and more. You get the same logic with less code and fewer mistakes. It needs a build step (or the CDN script) and is not available in this page's sandbox, so the next snippets are read-only.

A worker with Workbox:

JavaScript
// sw.js (Workbox via a bundler)
import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { CacheFirst, NetworkFirst, StaleWhileRevalidate } from 'workbox-strategies';
import { ExpirationPlugin } from 'workbox-expiration';

cleanupOutdatedCaches();
precacheAndRoute(self.__WB_MANIFEST);          // list injected at build time

registerRoute(
  ({ request }) => request.mode === 'navigate',
  new NetworkFirst({ cacheName: 'pages', networkTimeoutSeconds: 3 })
);

registerRoute(
  ({ request }) => request.destination === 'image',
  new CacheFirst({
    cacheName: 'images',
    plugins: [new ExpirationPlugin({ maxEntries: 60, maxAgeSeconds: 30 * 24 * 60 * 60 })],
  })
);

registerRoute(
  ({ url }) => url.pathname.startsWith('/api/'),
  new StaleWhileRevalidate({ cacheName: 'api' })
);

Compare that to the hand-written functions you have seen: precacheAndRoute covers install, activate cleanup and the fetch for precached files; registerRoute with a strategy class replaces the router and strategy functions; ExpirationPlugin handles trimming and age limits.

A typical build config (workbox-build's injectManifest):

JavaScript
// workbox-config.js
module.exports = {
  globDirectory: 'dist/',
  globPatterns: ['**/*.{html,js,css,svg,png,woff2}'],
  swSrc: 'src/sw.js',
  swDest: 'dist/sw.js',
};

Whether you use Workbox or write your own, the concepts are the same. Learning them first, as you have, means you understand what the library does when something goes wrong.

Runtime caches vs. precache

Precache Runtime cache
Filled At install, ahead of time On first request
Contents App shell and known files Whatever users view
Updated By version / revision at release By strategy rules and expiry
Works offline on first reload Yes Only for files already visited
Size Fixed, controlled Can grow: needs limits

A balanced setup precaches the shell, the offline page and the critical assets, and uses runtime strategies for everything else.

Do not precache too much. Everything in the precache list is downloaded when the worker installs, even if the user never needs it. On mobile networks a 20 MB install hurts. Precache the shell; let images, videos and secondary pages cache at runtime.

Versioning checklist

  • Cache names contain a version or are managed by a library.
  • activate deletes old versions but only caches your own worker created (use a prefix).
  • Files have content hashes, or are requested with cache: 'reload' when installing.
  • sw.js is served with Cache-Control: no-cache.
  • You have an update flow: banner, skipWaiting on user action, controllerchange reload.
  • Runtime caches have size and age limits.

Check your own version cleanup

Run the stand-in below with different cache names. It shows what a prefix-based cleanup keeps and what it removes: the same rule you would use in activate.

JS Which caches survive activate?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is precaching?

    Precaching fills caches ahead of time, usually with the app shell.
  2. 2. Why might cache.addAll store a stale file?

    Use hashed file names or Request objects with cache: 'reload' to bypass the HTTP cache.
  3. 3. What does revisioning in precache lists achieve?

    Hashes identify unchanged files, so they are reused.
  4. 4. Why use a name prefix when deleting caches in activate?

    Shared origins may hold unrelated caches; only remove your own.
  5. 5. Which should you precache?

    Precache only what is needed for the app to start offline; use runtime caching for the rest.

Summary

  • Precaching stores the app shell in a versioned cache during install, so the first offline reload works.
  • On activate, delete only the old caches your worker owns.
  • Use hashed file names or cache: 'reload' to avoid storing stale copies, and diff revisions to download only changes.
  • Workbox generates precache lists, routes strategies and handles expiration; the concepts are the same as hand-written code.
  • Keep the precache small and give runtime caches limits.

Next: Offline Fallback Pages