sw-precache icon indicating copy to clipboard operation
sw-precache copied to clipboard

[question] how would I achieve this vanilla SW behavior with sw-precache?

Open tconroy opened this issue 7 years ago • 2 comments

So the below vanilla SW code does the following:

  • caches an offline-page.html file for later use.
  • intercepts fetch events:
    • 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)
                })
        )
    }
})

tconroy avatar May 11 '17 01:05 tconroy

Having same issue..

Srinivas72 avatar Jan 23 '18 02:01 Srinivas72

+

RomaSto avatar Dec 25 '18 08:12 RomaSto