Lesson overview · Free interview practice

Service Workers

Build offline-capable Progressive Web Apps.

Topics in the full lesson
  • Introduction to Service Workers
  • Registering a Service Worker
  • Caching Strategies
  • Implementing Offline Capabilities
  • Building a Simple PWA
  • Best Practices
  • Exercises

Practice Problems

Work through a question before revealing its explanation. These questions and answers are free; Premium adds the full lesson walkthrough, examples and implementation detail.

Completion marks record your own progress, not an automatically checked result. The task type does not determine whether it is optional.

TheoryEasy

Caching Strategies: Cache-First, Network-First, Stale-While-Revalidate

Question

What are the canonical Service Worker caching strategies, and when do you reach for each?

Take a moment to think about this before revealing the answer

Explain your reasoning or try an implementation before comparing answers.

TheoryEasy

Registering a Service Worker

Question

How do you register a Service Worker, and what does the registration object give you?

Take a moment to think about this before revealing the answer

Explain your reasoning or try an implementation before comparing answers.

TheoryEasy

The Service Worker: A Network Proxy

Question

What is a Service Worker, and how does it differ from a Web Worker? What does it actually let you do?

Take a moment to think about this before revealing the answer

Explain your reasoning or try an implementation before comparing answers.

TheoryHard

The Service Worker Lifecycle: install → waiting → activate → fetch + the Update Dance

Question

Walk through every state a Service Worker goes through from registration to control, and explain the "update dance" that makes new SWs replace old ones.

Take a moment to think about this before revealing the answer

Explain your reasoning or try an implementation before comparing answers.

CodingMedium

Offline Fallback: Page, Image, and API Strategies

Implement and check your solution in the stated environment before revealing the answer.

Question

Implement an offline fallback strategy that distinguishes navigation, image and API requests. Explain why one HTML fallback is wrong for all three.

Browser setup before you write the handler

This is core practice for this lesson's lifecycle and Cache API material. You need Request, Response, fetch, installation with waitUntil, request interception with respondWith and cache lookup. This is a browser service worker exercise, not a Node service-worker simulation.

Use the companion fixtures/server.mjs, fixtures/index.html, fixtures/offline.html, fixtures/offline.svg and fixtures/online.svg. The server serves only fixed exercise files and local test endpoints. Start it with Node 24.21.0:

node fixtures/server.mjs

Use an isolated browser profile or context. Open:

http://127.0.0.1:3055/practice/?candidate=starter

Loopback is a potentially trustworthy origin for this setup. Do not use file://, a shared application's origin or an existing unrelated server. The fixture also reserves 127.0.0.1:3056 for the cross-origin image check and IndexedDB practice. If a port is occupied, do not reuse its server.

The page registers /practice/sw.js?candidate=starter with scope /practice/. It waits for readiness and reloads if needed. Wait until the page says Controlled before testing. The supplied installation code must successfully precache /offline.html and /offline.svg in memoized-async-browser-fallback-v1. The files have HTML and SVG MIME types. A failed precache rejects installation rather than pretending offline readiness.

After editing the worker, restore the server, use the cleanup button and close every practice tab before reopening. Otherwise a waiting update can leave the previous worker active. A fresh isolated browser context is another option.

Routing contract

Only intercept same-origin GET requests from controlled clients. Leave non-GET and cross-origin requests to the browser's normal network handling. Classify matching requests in this order:

MatchOn successful network fetchOn rejected network fetch
URL pathname starts with /api/Return the response unchangedJSON { "error": "offline" }, status 503, content type application/json, Cache-Control: no-store
request.mode === "navigate"Return unchangedCached /offline.html
request.destination === "image"Return unchangedCached /offline.svg
Anything elseDo not call respondWithNormal network failure

An HTTP 404 or 503 is a response, not a rejected fetch. Preserve it. /apiary/ is not /api/. Test an actual img element, since fetch("image.svg") does not make an image-destination request. If the named fallback asset has disappeared from cache, return Response.error() rather than undefined or an unrelated response.

This is network-first fallback, not runtime response caching. It does not retry writes, queue mutations or implement a production service-worker update strategy. The provided clients.claim() is for this isolated exercise. Do not add skipWaiting() blindly to an existing application.

Observable local checks

Edit tasks/service-worker/starter.js. In the page:

  1. While online, use GET API and Load image. Expect status 200 and a 64 × 48 image.
  2. Select Simulate server connection failure. The server now closes real request sockets, while its fixture-control routes remain available. This is deliberate local failure injection, not a fake fetch implementation.
  3. API requests must show offline JSON with status 503. An image must load the 32 × 24 SVG. The uncached-page link must display the offline HTML.
  4. Restore the server before reloading or reinstalling. HTTP failures, POST bypass, cross-origin image bypass and cache-loss behavior are covered by checks/browser.mjs.

The automated author check uses real Chrome through the existing Puppeteer installation:

node checks/browser.mjs starter

It checks both browser exercises in fresh browser contexts and reports them separately. It needs Chrome at the executable path configured in that file, not a Node mock. Manual checks remain available through the supplied page.

After practice, restore the server and use the page's cleanup button. It unregisters only /practice/ and deletes only this exercise's cache. Close the controlled tabs, then stop your own fixture process with Ctrl-C. Do not clear another app's registrations or storage.

Starter: tasks/service-worker/starter.js

const CACHE_NAME = 'memoized-async-browser-fallback-v1'
const OFFLINE_PAGE = '/offline.html'
const OFFLINE_IMAGE = '/offline.svg'

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => cache.addAll([OFFLINE_PAGE, OFFLINE_IMAGE])),
  )
})

self.addEventListener('activate', (event) => {
  event.waitUntil(self.clients.claim())
})

self.addEventListener('fetch', (event) => {
  throw new Error('Implement request-specific network fallback')
})

Take a moment to think about this before revealing the answer

Explain your reasoning or try an implementation before comparing answers.

Explore the full Service Workers material

Premium includes the complete lessons and implementation references. Free practice questions remain available without a subscription.

All course tracks & premium content
From basics to advanced masterclasses
Built for JS/TS developers like you
Real-world tips & common pitfalls
Upgrade to Premium