Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 37 ยท Offline and Background Sync

Offline Fallback Pages

Show a friendly offline page instead of the browser's dinosaur: precache a fallback, catch failed navigations, and handle images and API calls too.

The simplest offline feature is also the one users notice most: when the network is gone, your app shows a page that belongs to you instead of the browser's error screen. A fallback page does not make the app fully offline, but it turns a dead end into a calm message with a retry button and maybe a list of things that still work.

In this lesson you will precache a fallback page, serve it only when a navigation fails, and add different fallbacks for images and data requests. The code that talks to the service worker is shown read-only, because service workers cannot register inside the sandboxed preview. Next to it you get runnable stand-ins that use small fake Cache and fetch objects so you can watch the decisions being made.

The three moving parts

An offline fallback needs three things:

  1. A page to show, for example /offline.html. It must be fully self-contained: inline CSS, no external fonts, and inline or precached images.
  2. A place where that page is stored before the network disappears. That is the install event of the service worker.
  3. A fetch handler that tries the network first for navigations and falls back to the stored page only when the request fails.
flowchart LR
  A["Browser navigates to /articles"] --> B["Service worker fetch event"]
  B --> C{"Network OK?"}
  C -->|"yes"| D["Return the real page"]
  C -->|"no / timeout"| E["Return cached /offline.html"]

The fallback only appears when the network fails; online users never see it.

Precaching the fallback

Open a versioned cache in install and add the fallback together with everything it needs. If any request in addAll fails, the whole install fails, which is what you want: a service worker without its fallback is worse than none.

JavaScript
// sw.js (read-only, runs in a real service worker)
const CACHE = "shell-v1";
const OFFLINE_URL = "/offline.html";

self.addEventListener("install", (event) => {
  event.waitUntil(
    caches.open(CACHE).then((cache) =>
      cache.addAll([OFFLINE_URL, "/css/offline.css", "/img/offline.svg"])
    )
  );
  self.skipWaiting();
});

Catching failed navigations

A navigation request has request.mode === "navigate". Only those get the HTML fallback. Other requests (scripts, images, JSON) need their own answers.

JavaScript
// sw.js (continued)
self.addEventListener("fetch", (event) => {
  if (event.request.mode !== "navigate") return;

  event.respondWith(
    (async () => {
      try {
        return await fetch(event.request);
      } catch (error) {
        const cache = await caches.open(CACHE);
        return cache.match(OFFLINE_URL);
      }
    })()
  );
});

Two details matter here. First, fetch() only rejects on a network failure, not on a 404 or 500, so a server error page is still shown to the user as is. Second, returning from fetch handlers without calling respondWith lets the browser handle the request normally, which is the safest default for everything you do not understand yet.

Calling fetch inside the worker makes the user wait for the network to time out before the fallback appears. On a flaky connection that can take many seconds. A race with a timeout, shown below, keeps the wait short.

Try it: the fallback decision

This stand-in builds a tiny fake cache and a fake network that can be switched off. The handleNavigation function is the same logic as the real handler.

JS Navigation with an offline fallback

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Timeouts: do not make users wait

On a bad connection the request does not fail, it hangs. Race the network against a timer and fall back when the timer wins:

JavaScript
function timeout(ms) {
  return new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), ms));
}

const response = await Promise.race([fetch(event.request), timeout(4000)]);

Pick the timeout with care. Too short and users on slow mobile networks always get the fallback; too long and the fallback is useless. Three to five seconds for HTML is a common starting point.

Different fallbacks for different requests

An HTML page is not the right answer for a failed image or API call. Decide by request.destination (or by URL for APIs):

JS Fallbacks by request type

Press Run (or Ctrl + Enter) to see the console output here.

No output.

For API requests, a JSON body with an error field lets your page code show a message instead of crashing on a rejected promise. A null for scripts and styles means the page simply fails to load that resource, which is correct: a fake script would be worse than an error.

Starting a service worker takes time, and during that time the page request waits. Navigation preload lets the browser start the network request in parallel with worker startup:

JavaScript
self.addEventListener("activate", (event) => {
  event.waitUntil(self.registration.navigationPreload?.enable());
});

// in the fetch handler, prefer the preloaded response:
const preloaded = await event.preloadResponse;
if (preloaded) return preloaded;
return fetch(event.request);

It matters most for network-first navigation, where the worker adds latency without adding any value.

Telling the user what works offline

A good offline page is more than "No connection." Consider showing:

  • A Retry button (location.reload()).
  • Links to pages you know are cached, such as saved articles or the notes list.
  • A short, honest message: what happened, what still works, and that changes will sync later if you built that feature (see the offline outbox pattern).

Avoid relying on navigator.onLine. It reports true whenever the device is connected to a network, even a hotspot with no internet. Use it as a hint, and treat failed requests as the truth. The online and offline window events are fine for updating a small banner.

Common mistakes

  • Forgetting to precache the CSS or images the offline page uses, so it renders unstyled.
  • Returning the fallback for every request type, which breaks images and scripts in confusing ways.
  • Serving the fallback for HTTP errors; fetch resolves for those, so check response.ok if you want custom error pages.
  • Never versioning the cache name, so a changed offline.html never reaches users. See updating a PWA.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does fetch() reject its promise?

    fetch resolves for 404 and 500 responses. It rejects for network-level failures, which is what the fallback logic catches.
  2. 2. Which event is the right place to store the offline page?

    install runs once per worker version and can wait on the cache with event.waitUntil, so the page is stored before the worker takes control.
  3. 3. Why should an offline JSON error be returned for failed API calls instead of the HTML fallback page?

    The caller parses the response as JSON; an HTML page would cause a parse error instead of a clear offline message.
  4. 4. What does navigation preload do?

    The browser fires the network request while the worker boots, so the worker's startup delay does not add to page load time.

Summary

  • Precache a self-contained /offline.html in install and fail the install if it cannot be stored.
  • Answer only navigate requests with the HTML fallback; use other fallbacks (SVG, JSON, nothing) for other request types.
  • fetch rejects on network failure, not on HTTP errors; hanging requests need a timeout.
  • Enable navigation preload to hide worker startup time.
  • Do not trust navigator.onLine; trust failed requests.

Next: Offline Data with IndexedDB