Lesson 0004 · ~10 minutes

Fetch interception

One skill: use the fetch event + respondWith to own the response for a controlled page — cache, network, or fake — without re-learning full strategy catalogs.

Win (do this, then stop)

Finish 4 quiz cards. You can say: “If we call respondWith, we supply the Response; if we don’t, the browser goes network as usual.”

You already know

1. The interception pipe

  1. Page is controlled (has a controller).
  2. Something requests a URL (navigation, script, image, fetch()).
  3. SW gets a fetch event with event.request.
  4. Either you call event.respondWith(…) with a Response / promise — or you don’t, and the browser continues normally.

Sources: MDN respondWith, Offline Cookbook.

2. Smallest useful handler

self.addEventListener("fetch", (event) => {
  event.respondWith(
    caches.match(event.request).then((cached) => {
      return cached || fetch(event.request);
    })
  );
});

3. Three answer sources

Cache

caches.match(request) — offline / fast path.

Network

fetch(request) — live data; can also put a clone for next time.

Synthetic

new Response("offline", { status: 503 }) — your own fallback page or JSON.

Clone rule

Response body is single-use. If you return it and cache.put, use response.clone() ((Offline Cookbook).

4. Navigation vs subresource

Same event type. Different product meaning:

Default design rule

Precached shell → often cache-first (or navigate → shell). Fresh API data → network-first or network-only. Don’t run one strategy on the whole origin blindly.

5. Quiz (4 cards — required work)

1 of 4

A controlled page requests /app.js. Your fetch listener runs but never calls respondWith. What happens?

2 of 4

You want the SW to supply the response for this request. Which call?

3 of 4

Handler fetches from network, returns the response, and also cache.puts it. What must you do?

4 of 4

You only want special offline shell handling for full page loads. Best request check?

6. Keep these four lines

  1. Controlled client → fetch event may fire.
  2. respondWith = you own the Response.
  3. No respondWith = normal network path.
  4. Clone if you both return and put.
Ask your teacher Opaque responses, SPA fallback to index.html, or “why isn’t my fetch handler running?” — one question in chat is enough.

Primary (optional, ~10 min)

Offline Cookbook — skim “cache and network race / cache falling back to network” patterns. Strategy depth already exists on your Cache API track.