除了提示用户新版本可用之外,您还可以扩展“激活”事件侦听器以在发布新的 serviceworker 版本时删除旧缓存。
- 添加版本和名称变量
var version = "v3" // increase for new version
var staticCacheName = version + "_pwa-static";
var dynamicCacheName = version + "_pwa-dynamic";
- 删除缓存,当它们的名称不适合当前版本时:
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(cacheName) {
if (!cacheName.startsWith(staticCacheName) &&
!cacheName.startsWith(dynamicCacheName)) {
return true;
}
}).map(function(cacheName) {
console.log('Removing old cache.', cacheName);
return caches.delete(cacheName);
})
);
})
);
});
(学分:https ://stackoverflow.com/a/45468998/14678591 )
为了使 iOS safari 浏览器和“书签”PWA 也可以使用,我刚刚添加了 @jbone107 略微简化的功能:
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(cacheName) {
if (!cacheName.startsWith(staticCacheName) &&
!cacheName.startsWith(dynamicCacheName)) {
return true;
}
}).map(function(cacheName) {
// completely deregister for ios to get changes too
console.log('deregistering Serviceworker')
if ('serviceWorker' in navigator) {
navigator.serviceWorker.getRegistrations().then(function(registrations) {
registrations.map(r => {
r.unregister()
})
})
window.location.reload(true)
}
console.log('Removing old cache.', cacheName);
return caches.delete(cacheName);
})
);
})
);
});
这样你只需要增加版本号,更新由 serviceworker 自动完成。