GoogleChromeLabs / sw-precache

[Deprecated] A node module to generate service worker code that will precache specific resources so they work offline.
https://developers.google.com/web/tools/workbox/guides/migrations/migrate-from-sw
Apache License 2.0
5.22k stars 388 forks source link

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

Open tconroy opened 7 years ago

tconroy commented 7 years ago

So the below vanilla SW code does the following:

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)
                })
        )
    }
})
Srinivas72 commented 6 years ago

Having same issue..

RomaSto commented 5 years ago

+