Search⌘ K
AI Features

The Offline-Fallback Page

Explore how to create and cache an offline fallback page in your PWA to handle failed network requests gracefully. Learn to implement a user-friendly page that appears when resources are unavailable offline, enhancing reliability and providing a native app-like experience.

Background

A situation arises in providing offline availability to the user with the help of caching when the user is offline, and we don’t have the requested asset in the cached form. In this scenario, the user will see the network error, “This site can’t be reached,” because the network request will fail offline.

A straightforward workaround is to add a catch() block to the fetch method to handle any errors.

Javascript (babel-node)
self.addEventListener('fetch', event => {
event.respondWith(
// check the cache for the request
caches.match(event.request)
.then(response => {
// if finds the resource in the cache, return it
if (response) {
return response;
} else {
// else request to the network
return fetch(event.request)
.then(res => {
cache.put(event.request.url, res);
return res;
})
// adding a catch block to handle any network errors
.catch(err => {
console.log("Error while making network request!", err);
});
}
})
);
});

However, a better solution for this situation is to show a ...