Lesson 0004 · ~10 minutes
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.
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.”
fetch()).fetch
event with
event.request.
event.respondWith(…)
with a Response / promise — or you don’t, and the browser
continues normally.
Sources: MDN respondWith, Offline Cookbook.
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then((cached) => {
return cached || fetch(event.request);
})
);
});
fetch).respondWith right away in the
handler (don’t await something first, then call it late).
caches.match(request) — offline / fast path.
fetch(request) — live data; can also
put a clone for next time.
new Response("offline", { status: 503 }) — your own
fallback page or JSON.
Response body is single-use. If you return it and
cache.put, use
response.clone()
((Offline Cookbook).
Same event type. Different product meaning:
event.request.mode === "navigate" → document load (HTML
shell policy).
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.
A controlled page requests /app.js. Your
fetch listener runs but never calls
respondWith. What happens?
You want the SW to supply the response for this request. Which call?
Handler fetches from network, returns the response, and also
cache.puts it. What must you do?
You only want special offline shell handling for full page loads. Best request check?
fetch event may fire.respondWith = you own the Response.respondWith = normal network path.put.index.html, or “why isn’t
my fetch handler running?” — one question in chat is enough.
Offline Cookbook — skim “cache and network race / cache falling back to network” patterns. Strategy depth already exists on your Cache API track.