问题
I wish to make sure to clear all local cache when a new service-worker is loaded by the client. In my app the cache will often hold the old assets in cache even if the service-woker is updated. This causes a lot of unwanted behaviours.
I am using webpack v4.41 and workbox v6 to create my service-worker.js
.
I have read the documentation for workbox-expiration, but still do not understand how to clear the cache manually (the "Advanced Usage" section).
app.js
const wb = new Workbox('/service-worker.js');
let registration;
// I wish for this function to clear all cache
// by using "await expirationManager.expireEntries();"
const refreshCacheAndReload = () => {
if (caches) {
caches.keys().then((names) => {
for (const name of names) {
caches.delete(name);
}
});
}
// delete browser cache and hard reload
window.location.reload();
};
const showSkipWaitingPrompt = (event) => {
if (window.confirm("New version available! Refresh?")) {
wb.addEventListener('controlling', (event) => {
refreshCacheAndReload();
});
if (registration && registration.waiting) {
messageSW(registration.waiting, {type: 'SKIP_WAITING'});
}
}
}
service-worker-base.js
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate } from 'workbox-strategies';
import { CacheExpiration, ExpirationPlugin } from 'workbox-expiration';
// Cache then network for css
registerRoute(
'/dist/main.css',
new StaleWhileRevalidate({
cacheName: 'css',
plugins: [
new ExpirationPlugin({
maxEntries: 10, // Only cache 10 requests.
maxAgeSeconds: 60 * 60 * 24 * 7 // Only cache requests for 7 days
})
]
})
)
The documentation states that "Whenever you update a cached entry, you need to call the updateTimestamp() method so that its age is updated."
await openCache.put(
request,
response
);
await expirationManager.updateTimestamp(request.url);
I might be daft, but I cannot figure out how to apply this code to my project. I am missing a comprehensible example to understand how to force the cache to clear on service-worker update.
How and where should updateTimestamp()
and expireEntries()
be performed?
Kind regards /K
来源:https://stackoverflow.com/questions/65276766/clear-cache-using-workbox-expiration-in-workbox-6-0-2