if the fetch event is a navigation event, and the fetch fails, serve offline-page.html.
otherwise, serve from cache (if available), last resort hit the network
I can't seem to find a way to get this exact behavior with sw-precache. It seems to want to assume an app-shell-like architecture. Right now I really just want this one static page served for all routes when the user is offline, otherwise hit the cache/network and continue as normal, & respect redirects.
/*******************************************************************************
* Service Worker Install Event
******************************************************************************/
this.addEventListener('install', function (event) {
event.waitUntil(
caches.open(currentCache.offline).then(function(cache) {
return cache.addAll([
offlineUrl
])
}).then(function () {
return self.skipWaiting();
})
)
})
/*******************************************************************************
* Service Worker Activate Event
******************************************************************************/
this.addEventListener('activate', function (event) {
return self.clients.claim();
});
/*******************************************************************************
* Service Worker Fetch Event
******************************************************************************/
this.addEventListener('fetch', function (event) {
var userNavigating = event.request.mode === 'navigate' ||
(event.request.method === 'GET' &&
event.request.headers.get('accept').includes('text/html'));
if (userNavigating) {
event.respondWith(
fetch(event.request.url)
.catch(function (error) {
// return the offline page.
return caches.match(offlineUrl);
})
);
} else {
// respond with everything else if we can, first from cache
// then from network.
event.respondWith(
caches.match(event.request)
.then(function (response) {
return response || fetch(event.request)
})
)
}
})
So the below vanilla SW code does the following:
offline-page.html
file for later use.offline-page.html
.I can't seem to find a way to get this exact behavior with sw-precache. It seems to want to assume an app-shell-like architecture. Right now I really just want this one static page served for all routes when the user is offline, otherwise hit the cache/network and continue as normal, & respect redirects.