0

sw.js我有这个从互联网上获得的服务工作者文件 ( ):

const PRECACHE = 'precache-v1.1';
const RUNTIME = 'runtime';

// A list of local resources we always want to be cached.
const PRECACHE_URLS = [

  /* index page */
  'index.html', './',

  /* stylesheets */
  './assets/css/bootstrap.min.css', './assets/css/style.css', 

  /* javascripts */
  './assets/js/scripts.js', 

  /* images */
  './assets/images/logo.png'

];

// The install handler takes care of precaching the resources we always need.
self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(PRECACHE)
      .then(cache => cache.addAll(PRECACHE_URLS))
      .then(self.skipWaiting())
  );
});

// The activate handler takes care of cleaning up old caches.
self.addEventListener('activate', event => {
  const currentCaches = [PRECACHE, RUNTIME];
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return cacheNames.filter(cacheName => !currentCaches.includes(cacheName));
    }).then(cachesToDelete => {
      return Promise.all(cachesToDelete.map(cacheToDelete => {
        return caches.delete(cacheToDelete);
      }));
    }).then(() => self.clients.claim())
  );
});

// The fetch handler serves responses for same-origin resources from a cache.
// If no response is found, it populates the runtime cache with the response
// from the network before returning it to the page.
self.addEventListener('fetch', event => {
  // Skip cross-origin requests, like those for Google Analytics.
  if (event.request.url.startsWith(self.location.origin)) {
    event.respondWith(
      caches.match(event.request).then(cachedResponse => {
        if (cachedResponse) {
          return cachedResponse;
        }

        return caches.open(RUNTIME).then(cache => {
          return fetch(event.request).then(response => {
            // Put a copy of the response in the runtime cache.
            return cache.put(event.request, response.clone()).then(() => {
              return response;
            });
          });
        });
      })
    );
  }
});

在我网站的每个页面上,比如index.html, about.html, contact.html,我都有以下代码:

if('serviceWorker' in navigator) { navigator.serviceWorker.register('sw.js'); }

我在每个页面上都有此代码的原因是因为我的网站上有很多页面,并且如果用户登陆我网站的任何页面,我希望浏览器缓存所有文件。

现在举个例子,当用户访问 时about.html,Service Worker 会缓存列出的所有文件sw.js并缓存当前页面,即使它没有列出在sw.js. 这正是我想要的,因为我的网站上有数百个页面,我不想在sw.js文件中手动列出所有这些页面。问题是,当我sw.js更新. 每当用户再次访问此页面时,都会显示旧文件,而所有其他文件都是新文件。sw.jsabout.htmlabout.html

我该如何克服这个问题?我想绝对删除我的网站缓存的所有文件,而不仅仅是列出的文件sw.js,因为about.html没有列出,所以这个缓存的页面不会更新。

4

1 回答 1

2

问题是您的 about.html 文件保存在名为runtime的缓存中,该缓存未进行版本控制。所以这个缓存仍然是一样的,即使你部署了一个新的 sw.js 并增加了PRECACHE -cache。(例如 precache-v1.2)

解决方案是将版本控制添加到运行时-cache 以及:

const PRECACHE = 'precache-v1.1';
const RUNTIME = 'runtime-v1.1';

或者在激活时清理运行时缓存:

self.addEventListener('activate', event => {
// only PRECACHE (which is already the new version, setup on install event) should not be deleted.
const currentCaches = [PRECACHE];
...
于 2019-04-04T20:58:54.630 回答