Step-by-step introduction to the Service Worker API.
As the Service Worker sits between the page and the network, we can also serve a fallback page when fetching it from the server fails. We do have to make sure to only serve a fallback HTML page when the request is a GET HTML request.
// in sw.js
this.addEventListener('fetch', event => {
event.respondWith(
fetch(event.request).catch(fallback)
);
function fallback() {
if (isGetHtmlRequest(event.request)) {
return caches.match('/fallback.html')
}
}
});
function isGetHtmlRequest(request) {
return (
request.method === 'GET' &&
request.headers.get('Accept').contains('text/html')
);
}