如何使用 URL 删除服务工作进程缓存



我有这个从互联网上得到的服务工作者文件(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.htmlabout.htmlcontact.html,我有这个代码:

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

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

现在,例如,当用户访问about.html时,服务工作者会缓存sw.js中列出的所有文件,并且还会缓存当前页面,即使它未在sw.js中列出。这正是我想要的,因为我的网站上有数百个页面,我不想在sw.js文件中手动列出所有这些页面。问题是,当我更新sw.js中的版本号时,浏览器会删除sw.js中列出的所有旧缓存,并再次重新缓存文件,除了about.html。每当用户再次访问此页面时,都会显示旧about.html,所有其他文件都是新文件。

如何克服此问题?我想绝对删除我的网站缓存的所有文件,而不仅仅是sw.js中列出的文件,并且由于未列出about.html,因此此缓存页面不会更新。

问题是您的 about.html 文件保存在名为运行时的缓存中,该缓存未进行版本控制。所以这个缓存仍然是相同的,即使你部署一个新的sw.js递增的PRECACHE缓存。(例如预缓存-v1.2)

解决方案是将版本控制也添加到运行时缓存中:

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];
...

最新更新