Configuration of service worker

Asked

Viewed 114 times

5

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

When I unregister the application 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;
                    });
                }
            });
        })
    );
});

1 answer

1

The idea is to create a promise that says what happens when the notfound or error returns the function that adds something specific like this

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();
    });})

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.