我需要"清除"或"无效"每次发布后都有Workbox SW缓存。
这是我打算做的(当然是虚拟版),但我没有足够的经验来理解这是否是正确的方法:
importScripts(...);
const version = 1;
const workboxSW = new WorkboxSW();
workboxSW.router.registerRoute(/\.(?:png|gif|jpg|svg|json|js|css|woff|mp3)$/,
workbox.strategies.cacheFirst({
cacheName: 'static-cache-' + version
})
);
并在每个版本增加版本:) 我应该从以前的版本中清除每个文件吗? 有不同的方法吗?
tnx的反馈
答案 0 :(得分:5)
This makes sense to me, but you should make sure that when the activate event occurs, your clear any old caches you don't need.
A very basic approach (assuming you are ok with completely clearing the cache) is to wipe any caches that currently exist).
// Clean up caches in activate event to ensure no pages
// are using the old caches.
self.addEventListener('activate', (event) => {
const promiseChain = caches.keys()
.then((cacheNames) => {
// Step through each cache name and delete it
return Promise.all(
cacheNames.map((cacheName) => caches.delete(cacheName))
);
});
// Keep the service worker alive until all caches are deleted.
event.waitUntil(promiseChain);
});
You might want to be smarter with this logic (i.e. check for version number or only delete cache names you are aware of).
答案 1 :(得分:0)
如果您希望采用缓存优先策略,那么我建议将Workbox集成到您的构建过程中,并使用其内置支持生成"预先缓存清单&#34 ;。此清单将确保每次重新部署Web应用程序时,预先存档的文件都保持最新。
有一些指南可以在https://developers.google.com/web/tools/workbox/#get_started
开始构建时集成如果您选择不这样做,那么我建议不要使用缓存优先策略,而是先使用网络优先等。