Javascript ServiceWorker刷新加载工作的页面

Javascript ServiceWorker刷新加载工作的页面,javascript,service-worker,progressive-web-apps,Javascript,Service Worker,Progressive Web Apps,我想从离线功能中获益,所以我要确保在页面上缓存它自己和其他资产,如css和js self.addEventListener('install', function (event) { event.waitUntil(caches.open(cacheName).then(cache => cache.addAll([ "/", self.location.href ]))); self.skipWaiting(); }); 由于安

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

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

    self.skipWaiting();
});

由于安装只会为worker运行一次,我如何确保每次运行或至少不时刷新这些资产

虽然使用vanilla JS实现缓存过期可能有点困难,但您可以尝试使用Google。它有
缓存过期
的概念

一个超级基本的例子:

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

您可以阅读更多信息。

虽然使用vanilla JS实现缓存过期可能有点困难,但您可以尝试使用Google。它有
缓存过期
的概念

一个超级基本的例子:

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

您可以阅读更多信息。

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

//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文件仍然很旧,并且此组合可能无法很好地配合使用。

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

//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文件仍然很旧,并且这个组合可能无法很好地发挥作用