保留预缓存,同时删除 workbox service worker 中的其他缓存
Keep the precache while deleting other cache in workbox service worker
我正在使用下面的代码来清除 workbox 创建的缓存,但它也会删除由 workbox 自己管理的预缓存。
如果有更好的方法请告诉我。
// 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);
});
下面的代码可以很好地删除其他缓存,同时将预缓存保留在 workbox service worker 中。
// Clear old caches
var clearOldCaches = function (event)
{
event.waitUntil(
caches.keys().then(function (cacheNames) {
let validCacheSet = new Set(Object.values(workbox.core.cacheNames));
return Promise.all(
cacheNames
.filter(function (cacheName) {
return !validCacheSet.has(cacheName);
})
.map(function (cacheName) {
return caches.delete(cacheName);
})
);
})
);
};
self.addEventListener("activate", function (event) {
clearOldCaches(event);
});
我正在使用下面的代码来清除 workbox 创建的缓存,但它也会删除由 workbox 自己管理的预缓存。
如果有更好的方法请告诉我。
// 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);
});
下面的代码可以很好地删除其他缓存,同时将预缓存保留在 workbox service worker 中。
// Clear old caches
var clearOldCaches = function (event)
{
event.waitUntil(
caches.keys().then(function (cacheNames) {
let validCacheSet = new Set(Object.values(workbox.core.cacheNames));
return Promise.all(
cacheNames
.filter(function (cacheName) {
return !validCacheSet.has(cacheName);
})
.map(function (cacheName) {
return caches.delete(cacheName);
})
);
})
);
};
self.addEventListener("activate", function (event) {
clearOldCaches(event);
});