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