The Offline-Fallback Page
Learn how to show a custom fallback page to the user when the app fails to fetch the requested asset.
We'll cover the following...
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.
Press + to interact
self.addEventListener('fetch', event => {event.respondWith(// check the cache for the requestcaches.match(event.request).then(response => {// if finds the resource in the cache, return itif (response) {return response;} else {// else request to the networkreturn 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 ...