A Website That Works With No Internet
A service worker offline page example from a real site: storing every public page, the browser differences and the rules that keep the cache polite.
On this page
Pull the cable. Keep reading. That was the whole requirement for the public side of this site, and it is a short sentence hiding a long afternoon. The tutorial service worker offline page example gets you a polite “you are offline” screen. I wanted the article you were about to click to be there as well, including one you had never opened.
Store the site, not the click
Why not simply keep what people visit? Most offline setups do. That works for an app you live in and does very little for a blog, where the next thing you want is by definition something you haven’t read. This site is small (about forty posts and project pages in production when the worker shipped), so the unit of caching is the whole public corpus.
The server publishes a manifest: every public page with a content hash and a title, a release id and a kill flag. The worker compares hashes with what it holds and fetches only the difference. For a post the hash comes from its edit stamp, and list pages hash all the edit stamps together, so publishing anything refreshes the lists. My first version mixed the release id into every hash, which sounds safe and would have made every returning reader download every page again after every deploy. It was fixed before the worker reached production. Now only a handful of pages that show data the hashes can’t see carry the release.
The worker itself is one file of plain JavaScript with no library and no build step. The browser runs it exactly as written, so what I read is what is installed. It lives inside tdaweb, the code behind this site.
A service worker offline page example, small
Opening a public page follows a short road.
flowchart TD
A["Reader opens a page"] --> B{"Network answers?"}
B -->|yes| C["Show the network's answer"]
B -->|no| D{"Page stored?"}
D -->|yes| E["Show the stored copy"]
D -->|no| F["Offline page lists<br/>what is stored"]Here is the skeleton of that road as a fresh sketch, far smaller than the real one. If service workers are new to you, MDN’s guide covers the lifecycle this leans on.
// A sketch, not this site's worker.
self.addEventListener("install", (event) => {
event.waitUntil(caches.open("pages").then((cache) => cache.add("/offline")));
});
self.addEventListener("fetch", (event) => {
if (event.request.mode !== "navigate") return;
event.respondWith(
fetch(event.request).catch(async () =>
(await caches.match(event.request)) ??
(await caches.match("/offline")) ??
Response.error(),
),
);
});The order matters more than the code.
Important
Network first, always. Serve the stored copy first and you have built a second cache that no CDN purge can reach, and one day you will fix a typo and watch it survive on a stranger’s laptop for a week.
Online, this worker changes nothing a reader receives. The stored copy speaks only when the network fails. The files with hashed names are already handled by the ordinary HTTP cache, which was doing a fine job before anyone wrote a worker.
One framework detail: the worker stores HTML and leaves Next’s component payloads alone. Offline, a click makes Next 16.4.6 log that it failed to fetch the payload and fall back to a browser navigation, which the worker answers from storage. You lose the smooth transition and keep the page.
Politeness rules
Downloading a whole website into someone’s browser is a thing you should be a little shy about.
Nothing starts on a first page view. The sync waits for a second signal: a later page load, or a navigation to another page. A tab merely becoming visible doesn’t count, since background tabs do that without anybody caring. If the browser reports Save-Data or a 2g connection, no pages are fetched (only Chromium reports either). When it does run, it takes only changed pages, three at a time and three requests a second, in idle time.
sequenceDiagram
participant P as Open page
participant W as Worker
participant S as Server
participant C as Storage
P->>W: second signal, sync please
W->>S: fetch the manifest
S-->>W: pages, hashes, kill flag
loop each page whose hash changed
W->>S: the page, then its files
W->>C: save the files
W->>C: save the HTML last
W->>C: record the hash
end
W-->>P: sync finishedThe three saving steps are the part to copy. Scripts, styles and fonts are required, images are optional, and a page’s hash is recorded only after everything it needs is in. Interrupt the sync anywhere and the next run carries on from the truth instead of from optimism.
On a local build with a seeded database of 660 listed pages, Chromium 151 stored the first 300 in 256 seconds with 819 requests and 35.2 MB, most of it the pages themselves.
What an answer is allowed to destroy
Offline storage has an unusual failure: a bad response from the server can delete good data on a reader’s device. So the worker is picky about what each answer means.
| The server says | What it means | Stored copy |
|---|---|---|
| a good page | here is the current version | replaced |
404, 410, redirect, no-store | gone or private | removed |
| server error, too many requests | bad moment | kept, retried later |
| a challenge from the network edge | about the connection | kept, retried later |
| a far shorter page list | fault upstream | nothing pruned |
The last row is the same suspicion applied to the list itself. If the manifest suddenly names far fewer pages than the device holds, the worker refuses to believe it. An empty list and a broken list look identical to naive code.
Failing politely matters too. A full disk, a “slow down” or a run of failures makes the worker back off before it asks again. And a storage error never becomes a page error: the response goes to the page before anything is written, and a write that throws is swallowed.
Three browsers, three personalities
Chromium behaved well enough to make me suspicious. Navigation preload, which lets the browser start a network request while the worker is still waking up, saves time there. In Firefox 155, with preload on and the server stopped, every navigation ended on Firefox’s own “Problem loading page”, including pages that were sitting in storage. A failed preload took the navigation down with it, whatever my handler answered.
| Browser | What the scripted runs showed | The answer |
|---|---|---|
| Firefox 155 | a failed preload loses a stored page | preload off |
| Firefox | worker stops mid sync | page keeps messaging |
| Chromium 151 | a declined preload navigation goes twice | return the preload response |
| Firefox, WebKit | Playwright’s offline switch is no outage | stop the server |
No feature test reveals the first one, so the worker checks the user agent for Firefox and turns navigation preload off. I don’t enjoy sniffing user agents. I enjoy offline pages that don’t open even less.
The second one has numbers. Firefox stops a worker about a minute after its last event, even with a sync still in progress. With one message and nothing else, 17 entries were stored after 281 seconds. So the page now sends a small “still here” message every 20 seconds while it is visible, for up to 15 minutes, and the 300 page sync finished in 257 seconds. Chromium has its own limit, stopping a worker whose single event has run for five minutes, and the same repeated message hands it a fresh event.
The double send is worth knowing before the navigation in question is a sign-in callback. This is where trust but verify stops being a poster and becomes a test plan. All of these figures come from scripted runs of Chromium, Firefox and WebKit builds.
Ship the exit first
A service worker is the one part of a website that keeps running after you take it back, so it needs an off switch from the first version.
The worker calls skipWaiting() and claims open pages, and there is no “new version available” toast. A waiting worker is a fix that hasn’t arrived. Because every online page comes from the network, swapping the worker underneath a reader costs them nothing. One catch I measured: a new worker still waits for the old one’s open event to end, so during a long first sync a replacement waited 230 seconds.
flowchart TD
K["Kill flag read<br/>from the manifest"] --> D["Delete stored pages and files"]
D --> U["Unregister the worker"]
U --> T["Open tabs left as they are"]
D -.-> R["Reading list kept"]The kill switch is a flag in the manifest, flipped with a restart and no rebuild. It reloads no tab, since a reload throws away whatever someone had typed, and it keeps the reading list, which belongs to the reader and can’t be downloaded again.
Warning
Write the removal before you need it. The day you need it, you will not be in a mood to design anything.