Service Workers not updating

后端 未结 2 740
抹茶落季
抹茶落季 2021-02-07 03:42

I have a service worker installed in my website, everything works fine, except when I push an update to the cached files, in fact; they stay catched forever and I seem to be una

2条回答
  •  南旧
    南旧 (楼主)
    2021-02-07 04:20

    After googling and watching some videos on udacity, I found that the intended behavior of the worker is to stay until the page it controls is closed and reopened again when the new service worker can take control.

    The solution was to force it to take control based on https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/skipWaiting the following solved the issue, even when it takes 2 reloads in order for the new worker to reflect the changes (that makes sense since the app is loaded before the new worker replaces the previous).

    self.addEventListener('install',function(e){
        e.waitUntil(
            Promise.all([caches.open(STATIC_CACHE_NAME),caches.open(APP_CACHE_NAME),self.skipWaiting()]).then(function(storage){
                var static_cache = storage[0];
                var app_cache = storage[1];
                return Promise.all([static_cache.addAll(CACHE_STATIC),app_cache.addAll(CACHE_APP)]);
            })
        );
    });
    
    self.addEventListener('activate', function(e) {
        e.waitUntil(
            Promise.all([
                self.clients.claim(),
                caches.keys().then(function(cacheNames) {
                    return Promise.all(
                        cacheNames.map(function(cacheName) {
                            if (cacheName !== APP_CACHE_NAME && cacheName !== STATIC_CACHE_NAME) {
                                console.log('deleting',cacheName);
                                return caches.delete(cacheName);
                            }
                        })
                    );
                })
            ])
        );
    });
    

提交回复
热议问题