The following are steps to handling a request for a page.
- If requested page doesn’t exist, 404 response.
- If it does, respond with file (image).
- If all of the above fails, server can’t be reached – works for offline responses.
self.addEventListener('fetch', function(event) {
event.respondWith(
fetch(event.request).then(function(response) {
if (response.status === 404) { // Using the network
return new Response("Error 404. File not found.");
}
return response;
}).catch(function() { // Without using the network
return new Response("Can't reach server!");
})
);
});
Rather than responding with the custom text:
return new Response("Error 404. File not found.");
you can respond with a file or an image:
return fetch('/imgs/dr-evil.gif');
Make sure that you have Update on reload
checked so you only need to refresh once to see the changes.