Skip to content
Tutorials Center
My learning

Topics

Lesson 107 of 156 ยท Browser APIs

Service Workers and the Cache API

Learn the service worker lifecycle (install, activate, fetch), the Cache API, and offline strategies like cache-first and stale-while-revalidate.

A service worker is a JavaScript file that the browser runs in the background, separate from any page. It sits between your site and the network: every request your pages make can pass through it, and it can answer from a cache, from the network, or from code it generates itself. That single idea makes offline support, instant repeat visits, background sync and push notifications possible. It's the foundation of a Progressive Web App (PWA).

Service workers are powerful and a bit unusual: they have no access to the DOM, they live independently of tabs, and they follow a strict lifecycle. This lesson explains that lifecycle, shows how to register and write a worker, introduces the Cache API that stores responses, and compares the standard caching strategies. Because browsers only allow service workers on HTTPS pages (and localhost), and because the editors on this site run in a sandbox that blocks them, the real worker code is read-only. The caching logic itself is plain JavaScript, so we run it against a stand-in cache.

Where to try it for real. Save the worker examples as files in a project, serve them from http://localhost, then use your browser's developer tools (Application panel, Service Workers section) to watch the lifecycle, simulate Offline, and click Unregister when you want a clean slate.

Registering a worker

A page asks the browser to install a worker with navigator.serviceWorker.register():

JavaScript
// Read-only: in your page's JavaScript (e.g. app.js)
if ("serviceWorker" in navigator) {
  window.addEventListener("load", async () => {
    try {
      const registration = await navigator.serviceWorker.register("/sw.js");
      console.log("Service worker registered, scope:", registration.scope);
    } catch (error) {
      console.error("Registration failed:", error);
    }
  });
}

Two rules come with registration:

  • Scope. A worker controls the pages at or below the folder it is served from. A file at /sw.js controls the whole site; one at /app/sw.js only controls /app/.... Put the file at the root unless you have a reason not to.
  • Same origin, HTTPS. The worker file must come from your own origin, and the page must be a secure context.

Registering is safe to repeat on every load: if the file hasn't changed, nothing happens.

The lifecycle

A worker moves through states, and each transition is an event you can handle inside the worker file.

stateDiagram-v2
  [*] --> Installing: register()
  Installing --> Installed: install event done
  Installing --> Redundant: install failed
  Installed --> Activating: no old worker in control, or skipWaiting()
  Activating --> Activated: activate event done
  Activated --> Redundant: replaced by a newer worker
  Activated --> [*]

A new worker installs, may wait for the old one to finish, then activates and starts receiving fetch events.

  1. install. Fires once for each new version of the file. This is where you pre-cache the files your app needs. If you pass a promise to event.waitUntil() and it rejects, the install fails and the worker is discarded.
  2. waiting. If an older worker is still controlling open tabs, the new one waits so that no page ever gets two different versions at once. It activates when all those tabs close, or immediately if you call self.skipWaiting().
  3. activate. Fires when the worker takes over. This is where you delete old caches. Call clients.claim() if you want the worker to control already-open pages right away, instead of from the next navigation.
  4. fetch. From now on, every request from controlled pages triggers a fetch event in the worker.

Updates are automatic: the browser re-fetches your sw.js in the background (at least once every 24 hours and on navigations), and if the file differs byte for byte, it installs the new version. This is why you version your cache names.

A minimal worker

A worker file is a normal script, but self is the worker's global scope, and you listen for events on it:

JavaScript
// Read-only: /sw.js
const STATIC_CACHE = "static-v1";
const PRECACHE = ["/", "/offline.html", "/css/app.css", "/js/app.js"];

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

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

self.addEventListener("fetch", (event) => {
  if (event.request.method !== "GET") return; // let everything else pass through

  event.respondWith(
    caches.match(event.request).then((cached) => cached ?? fetch(event.request)),
  );
});

event.waitUntil(promise) tells the browser "don't shut me down until this promise settles". event.respondWith(promise) supplies the response for a request; if you don't call it, the request goes to the network as usual. Because workers are shut down when idle and restarted on demand, never keep important state in global variables; use the Cache API, IndexedDB or the page.

The Cache API

caches is a global (available in pages and workers) holding named Cache objects. A cache maps Request objects to Response objects, which is different from the HTTP cache the browser manages itself: you decide what goes in, when it's updated and when it's removed.

Method What it does
caches.open(name) Open (or create) a cache
cache.add(url) / cache.addAll(urls) Fetch URLs and store the responses
cache.put(request, response) Store a response you already have
cache.match(request) Find a stored response (or undefined)
cache.delete(request) Remove one entry
caches.match(request) Search across all caches
caches.keys() / caches.delete(name) List and delete whole caches

A Response body can only be read once. When you want to both return a response and store it, store a response.clone(); otherwise the second use fails with "body already used".

JavaScript
// Read-only
const response = await fetch(event.request);
const copy = response.clone();
caches.open("pages-v1").then((cache) => cache.put(event.request, copy));
return response;

Only GET requests can be stored, and you should only store successful responses (check response.ok), or you'll serve cached error pages later.

Caching strategies

A strategy is your answer to "cache or network, and in what order?" Three cover most needs:

flowchart TD
  R["Request"] --> S{"Strategy"}
  S -->|"cache-first"| A["Cache hit?"]
  A -->|"yes"| A1["Return cached copy"]
  A -->|"no"| A2["Fetch, store, return"]
  S -->|"network-first"| B["Try network"]
  B -->|"works"| B1["Store, return fresh copy"]
  B -->|"fails"| B2["Return cached copy"]
  S -->|"stale-while-revalidate"| C["Return cached copy now"]
  C --> C1["Fetch in background and update the cache"]

Cache-first is fastest, network-first is freshest, stale-while-revalidate is a balance of both.

  • Cache-first. Best for files that never change for a given URL: fingerprinted CSS and JS (app.3f9a1c.js), fonts, versioned images. Instant, works offline, but never updates unless the URL changes.
  • Network-first. Best for content that must be current, like an API listing or HTML pages, with a cached copy as the offline fallback. Slower when the network is slow, because you wait for it.
  • Stale-while-revalidate. Respond with the cached copy immediately, then fetch a fresh one in the background so the next visit is up to date. A great default for avatars, non-critical JSON and unversioned assets.

There are two more: network-only (for logins, payments and anything that must never be stale) and cache-only (for pre-cached files).

The code for these strategies doesn't depend on service workers at all. This runnable version uses a Map as the cache and a fake network that you can switch offline and whose "server version" you can change:

JS Three strategies against a fake cache and network

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

No output.

Read the output carefully. cacheFirst #2 still shows server v1, because it never contacted the server. The offline networkFirst call returns the copy saved while online, and the request with no saved copy fails. SWR #2 returns v2, the old copy, while quietly fetching v3, which is what SWR #3 then shows.

Choosing a strategy per request

A real fetch handler looks at each request and picks. The request.mode, request.destination and the URL tell you what kind of request it is:

JS Routing requests to strategies and cleaning old caches

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

No output.

Notice the prefix filter in the cleanup. Caches are shared by every script on your origin, so deleting everything that isn't the current version could remove a cache that belongs to something else.

Offline fallback pages

When a navigation fails and nothing is cached, return a friendly page instead of the browser's dinosaur. Pre-cache /offline.html during install and use it as the last resort:

JavaScript
// Read-only
self.addEventListener("fetch", (event) => {
  if (event.request.mode !== "navigate") return;

  event.respondWith(
    fetch(event.request).catch(() => caches.match("/offline.html")),
  );
});

Updating your app without surprises

  • Version your cache names (static-v4) and delete old ones on activate.
  • Fingerprint your assets with a content hash in the file name, so cache-first never serves stale code.
  • Tell the user. Listen for registration.addEventListener("updatefound", ...) and show a "New version available - reload" button instead of silently swapping versions. If you use skipWaiting(), an open page may suddenly be served new files by a new worker, which can break pages that expect the old ones.
  • Don't cache the service worker file itself for long. Serve sw.js with Cache-Control: no-cache, or updates will be delayed.

Other things service workers can do

The same background context supports push notifications (a push server wakes the worker and it calls registration.showNotification()), background sync (retry a failed request when the connection returns) and message passing with pages via postMessage(). These need explicit user permission or are not available in every browser, so treat them as enhancements.

Pitfalls

  • A bug can lock users in. A worker that serves a broken cached page forever is hard to remove. Test updates and keep a simple "kill switch" worker ready that unregisters itself.
  • Do not cache everything. Cache GET requests only, check response.ok, and never cache responses with private user data on shared devices.
  • Opaque responses. Cross-origin no-cors responses are stored but unreadable and take up large padded quota. Avoid caching them unless you must.
  • Storage is limited and the browser may evict it under pressure; always handle the case where a cache is empty.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the purpose of event.waitUntil(promise) in an install handler?

    waitUntil extends the event's lifetime. If the work (such as pre-caching) rejects, the worker does not install.
  2. 2. Where should a service worker normally delete outdated caches?

    By activation the old worker no longer needs its caches, so it is safe to clean them up. Deleting in install could break pages still controlled by the old worker.
  3. 3. Which strategy returns the cached copy immediately and updates the cache in the background?

    Stale-while-revalidate trades a possibly stale answer for speed, and refreshes the cache for the next request.
  4. 4. Why do you call response.clone() before cache.put(request, response) when you also return the response?

    Both the browser (to read the body) and the cache consume the stream. Without a clone, the second use fails with a 'body already used' error.
  5. 5. A worker file lives at /app/sw.js. Which pages can it control by default?

    The default scope is the folder that contains the worker file. A worker at the root controls the whole origin.

Summary

  • A service worker is a background script between your pages and the network. It needs HTTPS (or localhost), a same-origin file, and a scope determined by its location.
  • The lifecycle is install (pre-cache), waiting, activate (delete old caches) and then fetch handling. Use event.waitUntil() to keep it alive and event.respondWith() to answer requests.
  • The Cache API (caches.open, add, put, match, delete) stores request/response pairs under names you control. Clone responses before storing them.
  • Choose a strategy per request: cache-first for versioned files, network-first for fresh data with an offline fallback, stale-while-revalidate for a balance. Always version cache names and handle updates gracefully.
  • Never keep state in worker globals, only cache successful GET responses, and serve the worker file itself without long caching.

Next: Fullscreen, Page Visibility and Screen Wake Lock - small browser APIs that react to the state of the page and the screen.