Workbox: clean up cache
Asked Answered
Y

1

10

It doesn't seem like workbox cleans up old caches. For example, if I specify a cache version like this:

var version = 'v2';
workbox.core.setCacheNameDetails({
  suffix: version
});

...I would have expected workbox to clean up older versions of the cache once the new service worker activates, but my cache storage looks like this:

enter image description here

Is it safe to manually clean up caches myself? For example in my service worker:

self.addEventListener('activate', function(event) {
  event.waitUntil(
    caches
      .keys()
      .then(keys => keys.filter(key => !key.endsWith(version)))
      .then(keys => Promise.all(keys.map(key => caches.delete(key))))
  );
});
Yeryerevan answered 7/4, 2018 at 7:56 Comment(0)
P
16

You are changing the suffix property value to a string that you are as a version. But Workbox only uses it to name the bucket for caching.

From the Workbox docs.

The main use case for the prefix and suffix is that if you use Workbox for multiple projects and use the same localhost for each project, setting a custom prefix for each module will prevent the caches from conflicting with each other.

Workbox doesn't think of x-v2 as the new replacement for x-v1.

You can use your cache eviction strategy just fine since Workbox will no longer use the previously named caches.

However you shouldn't need to use suffix to version your assets. Workbox has a number of tools to make sure assets are updated correctly. Plus your suffix implementation will always start out with a fresh cache and download everything.

precache

Precache has revisions for assets so as the assets change, you generate a new build, and deploy the changed assets will update and the unchanged assets will be left alone.

strategies

Strategies is where most of the work will be done. When you are defining routes you will define the caching strategy the fits best with that type of asset. staleWhileRevalidate is a great approach where the on-device cache will be used but Workbox will also hit the network in parallel and check if there are updates to that resource.

expiration

You can also make sure that old assets purged if they become older than the defined expiration length.

Pendentive answered 8/4, 2018 at 16:24 Comment(2)
Excellent answer! Thank you.Yeryerevan
Ok just to understand it again. I don't need to delete the cache, because Workbox is handling it automatically? My problem is that in my browser with a local host, I still need to delete the server worker manually, because it does not want to update the code, even though the precache file got a new name. Now I'm not sure if I should implement a safety clear like hereMultiply

© 2022 - 2024 — McMap. All rights reserved.