Configuration of service worker

5

Can you configure the code below the service worker to ignore the cache if the request that comes from the server is 200? My service worker is picking up routes that exist and are not cached and generating several errors in the application.

When I unregister the application it works perfectly.

var version = '0.8'; //Corrigido o erro de cache
self.addEventListener('install', function (event) {
    event.waitUntil(
        caches.open('v1').then(function (cache) {
            return cache.addAll([
                '/',
                '/css/app.css',
                '/js/app.js',
                '/cache.js',
                '/favicon.ico',
                '/js/gauge.min.js',
                '/manifest.json',
                '/avatar.png',
            ]);
        })
    );
});

self.addEventListener('fetch', function (event) {
    // if (handler) {
    //     event.respondWith(handler(event.request));
    // } else if (router.default && event.request.method === 'GET') {
    //     event.respondWith(router.default(event.request));
    // }
    event.respondWith(
        caches.open('mysite-dynamic').then(function (cache) {
            return cache.match(event.request).then(function (response) {
                if (response) {
                    return response;
                } else {
                    return fetch(event.request).then(function (response) {
                        cache.put(event.request, response.clone());
                        return response;
                    });
                }
            });
        })
    );
});
    
asked by anonymous 03.11.2017 / 15:08

1 answer

1

The idea is to create a promise that tells you what happens when you do notfound or error returning the function that adds something specific something like

self.addEventListener('install', function (event) {

return Promise.all(
    [
        caches.open(CACHE_VERSIONS.assets)
            .then(
                (cache) => {
                    return cache.addAll(BASE_CACHE_FILES);
                }
            ),
        caches.open(CACHE_VERSIONS.offline)
            .then(
                (cache) => {
                    return cache.addAll(OFFLINE_CACHE_FILES);
                }
            ),
        caches.open(CACHE_VERSIONS.notFound)
            .then(
                (cache) => {
                    return cache.addAll(NOT_FOUND_CACHE_FILES);
                }
            )
    ]
).then(() => {
        return self.skipWaiting();
    });})

It follows the link of how my service work is working well it can identify the situation of the file and direct it to something determined.

click the link and go to the JS option Example Service Work

    
17.08.2018 / 17:36