Offline Fallback Pages
You'll learn how to create and serve custom offline pages when both the network and cache fail.
When a user navigates to a page that isn't cached and the network is unavailable, your service worker can catch this failure and serve a friendly, branded offline page instead of the browser's harsh "no internet connection" dinosaur screen. This is the safety net for your offline-first strategy.
The Core Idea
Think of an offline fallback page as the "404 page" of connectivity failures. It's a pre-cached HTML file that you serve when:
- The user requests a page
- The network is down
- No cached version exists
You've already learned precaching and cache strategies. Now you combine them: precache your offline fallback page during the install event, then serve it as a last resort in your fetch event handler.
Implementation Pattern
In your install event, cache the offline page alongside your essential assets. Then in your fetch event, wrap your caching strategy in a catch block:
self.addEventListener('fetch', (event) => {
if (event.request.mode === 'navigate') {
event.respondWith(
fetch(event.request)
.catch(() => {
return caches.match(event.request)
.then((response) => response || caches.match('/offline.html'));
})
);
}
});
This checks for navigation requests (page loads), tries the network, falls back to cache, and finally serves your custom offline page if nothing else works.
Your /offline.html should be lightweight, informative, and ideally include inline CSS so it works without additional requests.
Key Takeaway: Offline fallback pages transform network failures into graceful experiences by serving a pre-cached, custom page when both network and specific content cache miss—turning errors into branded communication opportunities.