Service Worker 不更新

Service Workers not updating

我在我的网站上安装了一个 service worker,一切正常,除了我推送更新到缓存文件时,事实上;他们永远被抓住,我似乎无法使缓存无效,除非我从 `chrome://serviceworker-internals/

取消订阅工作人员
const STATIC_CACHE_NAME = 'static-cache-v1';
const APP_CACHE_NAME = 'app-cache-#VERSION';

const CACHE_APP = [
    '/',
    '/app/app.js'
]
const CACHE_STATIC = [
    'https://fonts.googleapis.com/css?family=Roboto:400,300,500,700',
    'https://cdnjs.cloudflare.com/ajax/libs/normalize/4.1.1/normalize.min.css'
]

self.addEventListener('install',function(e){
    e.waitUntil(
        Promise.all([caches.open(STATIC_CACHE_NAME),caches.open(APP_CACHE_NAME)]).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(
        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);
                    }
                })
            );
        })
    );
});

self.addEventListener('fetch',function(e){
    const url = new URL(e.request.url);
    if (url.hostname === 'static.mysite.co' || url.hostname === 'cdnjs.cloudflare.com' || url.hostname === 'fonts.googleapis.com'){
        e.respondWith(
            caches.match(e.request).then(function(response){
                if (response) {
                    return response;
                }
                var fetchRequest = e.request.clone();

                return fetch(fetchRequest).then(function(response) {
                    if (!response || response.status !== 200 || response.type !== 'basic') {
                        return response;
                    }
                    var responseToCache = response.clone();
                    caches.open(STATIC_CACHE_NAME).then(function(cache) {
                        cache.put(e.request, responseToCache);
                    });
                    return response;
                });
            })
        );
    } else if (CACHE_APP.indexOf(url.pathname) !== -1){
        e.respondWith(caches.match(e.request));
    }
});

其中#VERSION 是在编译时附加到缓存名称的版本;请注意 STATIC_CACHE_NAME 永远不会改变,因为文件被认为永远是静态的。

而且行为不稳定,我一直在检查删除功能(它记录的部分)并且它一直在记录已经删除的删除缓存(据推测)。当我 运行 caches.keys().then(function(k){console.log(k)}) 我得到一大堆应该被删除的旧缓存。

在谷歌搜索和观看一些关于 udacity 的视频后,我发现 worker 的预期行为是一直停留到它控制的页面关闭并在新的 service worker 可以控制时再次打开。

解决方案是强制它根据 https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/skipWaiting 进行控制以下解决了问题,即使需要重新加载 2 次才能让新工作人员反映更改(这很有意义,因为应用程序在新工作人员替换之前的工作人员之前加载。

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

作为一个 "service worker newbie" 我遇到了一个相关的情况,即使在 Chrome Canary 上启用了 "JavaScript Console>Application>Update on reload",service worker 也不会刷新。

问题是我的 /sw/index.js 中有工作代码,然后我向 /sw/index.js 引入了一个错误。当我引入错误时,浏览器拒绝加载更新的代码并继续加载早期工作的 service worker。当我更正 index.js 中的代码并刷新页面时,服务工作者的新代码出现了。我本以为错误填充的代码会抛出错误,但事实并非如此。浏览器刚刚加载了较早的无错误版本。