Show contents
Chapter 4 of 7 · 20 min
The service worker and offline
By the end of this chapter, you'll be able to
- Describe a service worker's lifecycle: install, activate, intercept
- Compare caching strategies: cache first, network first, stale-while-revalidate
- Choose a strategy according to the type of resource
- Version a cache so that updates get through
A go-between for the page and the network
A service worker is a JavaScript script running in the background, separate from the page. It goes through three steps:
- install (
install): it caches the essential files (the home page, the CSS, the icons); - activate (
activate): it deletes old caches that are no longer needed; - intercept (
fetch): every request from the page goes through it, and it decides where the answer comes from.
const CACHE = "market-prices-v3";
const ESSENTIALS = ["/", "/style.css", "/app.js", "/icons/192.png"];
self.addEventListener("install", (event) => {
event.waitUntil(caches.open(CACHE).then((cache) => cache.addAll(ESSENTIALS)));
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys().then((names) => Promise.all(names.filter((n) => n !== CACHE).map((n) => caches.delete(n)))),
);
});
self.addEventListener("fetch", (event) => {
event.respondWith(caches.match(event.request).then((cached) => cached ?? fetch(event.request)));
});
The page registers it with navigator.serviceWorker.register("/sw.js"). This code only runs in a browser, over HTTPS (or on localhost during development).
Three strategies
Let's simulate a cache and a network that can go down, to compare the strategies:
const network = { online: true, version: 2 };
const cache = new Map([["/prices", "prices v1"], ["/style.css", "css v1"]]);
async function fetchNetwork(url) {
if (!network.online) throw new Error("offline");
return `${url.slice(1)} v${network.version}`;
}
async function cacheFirst(url) {
return cache.get(url) ?? fetchNetwork(url);
}
async function networkFirst(url) {
try {
const response = await fetchNetwork(url);
cache.set(url, response);
return response;
} catch {
return cache.get(url) ?? "offline page";
}
}
console.log("online, cache first:", await cacheFirst("/prices"));
console.log("online, network first:", await networkFirst("/prices"));
network.online = false;
console.log("offline, network first:", await networkFirst("/prices"));
console.log("offline, unknown page:", await networkFirst("/weather"));
online, cache first: prices v1
online, network first: prices v2
offline, network first: prices v2
offline, unknown page: offline page
- cache first: instant and available offline, but may serve an outdated version (here, prices v1 while the network has v2). Ideal for files that rarely change: CSS, versioned scripts, icons, fonts;
- network first: always up to date online, falling back to the cache offline. Ideal for data that changes often: prices, news, messages;
- stale-while-revalidate: answers immediately from the cache, and updates the cache in the background for next time. A good compromise for content where a cache slightly behind is acceptable (avatars, rarely changing lists).
Without a network, the cache answers: the user sees the last known prices, with their date.
Text description of the animation
- The page asks for the prices, without knowing that a service worker exists.
- The service worker receives the request and applies its strategy.
- The network answers: the fresh response is sent to the page.
- Along the way, the cache is updated for the next outage.
- Without a network, the cache answers: the user sees the last known prices, with their date.
Offline, you must say so: show “Prices from 12 March, 8am, offline” rather than letting people believe the data is up to date.
Mini-lab: stale-while-revalidateJavaScript
Output
Click “Run” to execute your code.Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: choosing each resource's strategy
Write a function strategy(url) for the market prices app: static files (ending in .css, .js, .png or .woff2) cache first, addresses starting with /api/ network first, and everything else (the HTML pages) network first with a fallback to a /offline.html page cached at install time: "network first, fallback /offline.html".
Hint 1
/\.(css|js|png|woff2)$/ tests the end of the address.Hint 2
Show the solution and common mistakes
function strategy(url) {
if (/\.(css|js|png|woff2)$/.test(url)) return "cache first";
if (url.startsWith("/api/")) return "network first";
return "network first, fallback /offline.html";
}
for (const url of ["/style.css", "/icons/192.png", "/api/prices?market=kaolack", "/", "/help"]) {
console.log(`${url.padEnd(28)} → ${strategy(url)}`);
}
/style.css → cache first
/icons/192.png → cache first
/api/prices?market=kaolack → network first
/ → network first, fallback /offline.html
/help → network first, fallback /offline.html
Static files are safe cache first provided their name changes with each version (for example app.3f9c.js, which build tools do) or the cache is versioned. Data and pages go through the network when it is there; offline, an unknown page shows a clear message rather than a browser error.
Common mistakes:
- Putting
/api/calls cache first: the app would forever show the first prices it downloaded. - Testing
url.endsWith(".js")on an address with parameters (/app.js?v=3): it no longer ends in.js. Strip the parameters before testing.
Summary
- 1A service worker installs, activates, then intercepts the page's requests.
- 2Cache first for static files, network first for data that changes.
- 3Stale-while-revalidate answers fast and updates in the background.
- 4Offline, show the last known data and say so clearly.
- 5A versioned cache, cleaned up on activation, guarantees that updates get through.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.