服务工作者刷新加载工作的页面



我想从离线功能中受益,所以我确保在安装页面上缓存它自己和其他资产,如css和js。

self.addEventListener('install', function (event) {
    event.waitUntil(caches.open(cacheName).then(cache => cache.addAll([
        "/",
        self.location.href
    ])));
    self.skipWaiting();
});

由于安装只会为辅助角色运行一次,因此如何确保每次运行时或至少不时刷新这些资产?

您也可以通过在每次部署新版本的网站时定义新的缓存名称来实现此目的:

//change cache name with each deploy
var staticCacheName = 'NewWithEachDeploy';
self.addEventListener('install', function (event) {
  event.waitUntil(
    caches.open(staticCacheName).then(function (cache) {
      return cache.addAll([
        'index.html',
        '...'
      ]);
    })
  );
});

然后在激活时删除所有旧缓存。

self.addEventListener('activate', function (event) {
    event.waitUntil(caches.keys().then(function (keyList) {
        return Promise.all(keyList.map(function (cacheKey) {
            //delete all caches which do not equal with the current cache name (staticCacheName)
            if (cacheKey !== staticCacheName) {
                console.log('[ServiceWorker] Removing old cache', cacheKey);
                return caches.delete(key);
            }
        }));
    }));
});

这样,您可以确保一次更新所有资源。否则你可能会遇到麻烦。例如,您缓存的 html 已更新到最新版本,但 JS 文件仍然很旧,并且这个星座可能无法很好地协同工作。

虽然使用vanilla JS实现缓存过期可能有点挑战性,但您可以尝试使用Google的Workbox。它有这个概念 cache expiration .

一个超级基本的例子:

const cacheExpirationPlugin = new workbox.cacheExpiration.CacheExpirationPlugin({
  maxEntries: 50,
  maxAgeSeconds: 24 * 60 * 60
});

你可以在这里阅读更多关于它的信息。

最新更新