Your First Offline-Ready Website: A Service Worker Cache Strategy You Can Explain

A website that loses its connection should not automatically become a blank screen. For small tools, documentation pages and lightweight web apps, an offline shell can provide a useful interface while the network is unavailable.

Service workers make this possible. They are background scripts that can intercept requests from pages they control and return cached responses. That ability is powerful, but careless caching can also leave users with stale pages or expose private data on a shared device.

This tutorial creates a tiny offline-ready website with an intentionally narrow cache strategy. The goal is to know exactly what you are caching and why.

Understand three different browser storage systems

Service workers commonly work with the Cache Storage API, which stores request/response pairs. It is not the same as localStorage, which holds simple string key/value pairs, or IndexedDB, which is better suited to structured application data.

A useful division of responsibility is:

  • Cache Storage: public, versioned application files such as HTML, CSS, JavaScript and an offline page.
  • IndexedDB: structured offline records that the app deliberately saves and synchronizes.
  • Server: authoritative account data, permissions and transactions.

The Web2Generators article on localStorage, sessionStorage and cookies explains why session secrets should not casually be placed in browser storage. A service worker cache is not a private vault, and caching a response does not encrypt it.

Start with an intentionally small app

Create a folder with four files:

offline-demo/
  index.html
  app.css
  app.js
  sw.js

Use normal HTML and links. The page should work online even if its service worker fails to register:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Offline Demo</title>
  <link rel="stylesheet" href="./app.css">
  <script src="./app.js" defer></script>
</head>
<body>
  <main>
    <h1>Offline Demo</h1>
    <p>This page keeps a small app shell available offline.</p>
    <p id="status" role="status">Checking offline support...</p>
    <p><a href="./index.html">Return to the start page</a></p>
  </main>
</body>
</html>

In app.css, add a little responsive styling:

body {
  font: 1rem/1.6 system-ui, sans-serif;
  margin: 0;
  padding: clamp(1rem, 4vw, 3rem);
  color: #17212b;
  background: #fff;
}
main { max-width: 44rem; margin-inline: auto; }
a { color: #0754a6; }

This is deliberately plain. Offline behavior should not depend on a complex JavaScript framework or remote CSS package.

Register the service worker

In app.js:

const statusMessage = document.querySelector("#status");

if ("serviceWorker" in navigator) {
  window.addEventListener("load", async () => {
    try {
      await navigator.serviceWorker.register("./sw.js");
      statusMessage.textContent = "Service worker registered. Check installation in DevTools before testing.";
    } catch (error) {
      statusMessage.textContent = "Service worker registration failed.";
      console.error("Service worker registration failed:", error);
    }
  });
} else {
  statusMessage.textContent = "This browser does not support service workers.";
}

The registration promise does not prove that installation and precaching have finished. Check that the worker is activated in DevTools before testing offline. Registration also does not guarantee that the currently open page is controlled immediately. A newly installed service worker typically controls pages after a navigation or reload. Service workers require a secure context, such as HTTPS or the special local development origin http://localhost.

Cache just the application shell

Create sw.js:

const CACHE_PREFIX = "offline-demo-";
const CACHE_NAME = `${CACHE_PREFIX}v1`;
const SHELL = ["./", "./index.html", "./app.css", "./app.js"]
  .map((path) => new URL(path, self.registration.scope).href);

self.addEventListener("install", (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => cache.addAll(
      SHELL.map((url) => new Request(url, {
        cache: "reload",
        credentials: "omit"
      }))
    ))
  );
});

self.addEventListener("activate", (event) => {
  event.waitUntil(
    caches.keys().then((names) => Promise.all(
      names
        .filter((name) => name.startsWith(CACHE_PREFIX) && name !== CACHE_NAME)
        .map((name) => caches.delete(name))
    ))
  );
});

self.addEventListener("fetch", (event) => {
  const request = event.request;
  if (request.method !== "GET") return;
  if (!SHELL.includes(request.url)) return;

  event.respondWith((async () => {
    const cache = await caches.open(CACHE_NAME);
    if (request.mode === "navigate") {
      try {
        return await fetch(request);
      } catch {
        return (await cache.match(request)) || Response.error();
      }
    }
    return (await cache.match(request)) || fetch(request);
  })());
});

This example uses network first for navigation and cache first for the other shell requests. On a network failure, a navigation to the app’s start page uses its own cached response. HTTP errors such as 404 or 500 are still returned by fetch(); they do not trigger the offline fallback. A slow connection can also delay the network-first attempt.

The allowlist contains four exact URLs on the worker’s own origin, resolved relative to its registration scope. Other pages, APIs, query-string variants, non-GET requests and remote resources use the browser’s normal network handling. They are neither added to this cache nor replaced with the start page. On a multipage site, design a dedicated offline response instead of making a missing article look like the homepage.

All four entries must be public static files, served without personalized responses or login redirects. Installation requests omit credentials and use cache: "reload" to avoid reusing an old HTTP-cache entry when building a new shell. A failed addAll() makes installation fail; inspect DevTools before claiming offline support is ready.

Lookups use the current named cache, rather than caches.match(), which can search other caches on the origin. This keeps another app’s entries or a waiting worker’s cache from supplying this version’s responses. See MDN’s service worker guide for the lifecycle and CacheStorage.match() reference for that distinction.

Know what happens when you release version two

Browsers may keep an existing service worker active while clients it controls remain open. Updating the sw.js file allows the browser to discover a new worker, but that worker may wait until controlled pages close before becoming active. The example intentionally avoids skipWaiting() and clients.claim() so that a new worker does not unexpectedly replace the logic used by an open session.

When the static files change, update CACHE_NAME from v1 to v2. During installation, the new worker fetches the updated shell. During activation, it deletes older caches with the same application prefix. Use a prefix unique to this app; storage is shared across the origin, not isolated by service worker scope.

There is a subtle deployment hazard even without immediate activation: a network-first navigation can load new HTML while an old worker still serves cached JavaScript and CSS. Incompatible versions can break the page. Versioned URLs or content-hashed filenames are a better long-term approach for larger apps. Consider how updates are presented to users before adding aggressive activation shortcuts.

Test offline behavior instead of assuming it works

Use a local server, not a file:// URL. Run this command inside offline-demo/, with Python installed:

python3 -m http.server 8000

Open http://localhost:8000/ and inspect your browser DevTools:

  1. In Application > Service Workers (or equivalent), wait for activation, then reload and verify that the page is controlled.
  2. Inspect Application > Cache Storage and confirm only the planned shell entries exist.
  3. Enable the browser’s offline simulation and reload the page.
  4. Confirm the page remains usable without an external font, analytics script or API call.
  5. Return online, edit the stylesheet and change the cache version in sw.js. Trigger an update in DevTools or revisit the page. Observe the new worker waiting while the old one controls an open tab. Close all tabs for the demo and reopen it so the new version can activate; an ordinary reload may not release the old worker.
  6. Unregister the worker and clear site data, then ensure the page still works normally online.

Use the browser network-inspection guide to locate the Network panel and examine where responses came from. When debugging freshness, distinguish this explicit response cache from the separate HTTP cache and its Cache-Control/ETag rules. For remote HTML endpoints, the cURL Command Line Builder can help inspect ordinary HTTP responses; cURL itself does not run or test a browser service worker.

Common pitfalls that appear only after launch

Caching authenticated HTML. Avoid storing account pages, checkout confirmations, or private API responses in shared cache names. Cache Storage is origin-scoped and available to scripts running on that origin; it is not an access-control layer.

Caching remote assets implicitly. A cache-first strategy for every request may accidentally retain third-party scripts or responses that were not intended for offline reuse. Keep an explicit allowlist.

Treating connectivity as a boolean. navigator.onLine is only a hint. Network requests can fail while the browser reports online, or a local network can exist without internet access. Handle failures at the request level.

Forgetting storage limits. Browsers may evict site storage under pressure. Offline mode should degrade gracefully; permanent storage is not guaranteed.

Assuming a PWA manifest makes a site offline-ready. The manifest describes app identity and installation-related behavior. It does not implement the caching strategy. The Web2Generators article on the Web App Manifest Working Draft is a useful companion, but these features serve different jobs.

Making an offline page look like live data. If your UI shows cached information, label its age or status. For anything financial, medical or permission-sensitive, do not silently present obsolete information as current.

When to add offline editing

Read-only pages and small tools are a good first step. Offline editing requires more: a durable local database, an explicit queue, conflict resolution, retries, user-visible sync states and a plan for sign-out. Do not treat a queued write as successfully committed just because the form accepted it locally.

For complex API workflows, a simple state diagram made in the Mermaid Live Editor can help distinguish “saved locally,” “waiting to sync,” “confirmed by server” and “conflict requires review.”

Start with the four-file example and verify its Cache Storage entries. Expand the allowlist only when there is a clear offline user need.

Premium is coming soon

An optional premium subscription to remove ads is planned. Subscriptions are not available yet.

You can keep using our free tools without an account.