DEV Community

Discussion on: Service workers and caching strategies explained

Collapse
 
martinrojas profile image
martin rojas

This is really helpful. Been running into an issue with a site that used to be Gatsby and I am replacing with Nuxt. However they Gatsby site had service workers. Is there a way to invalidate those and load the new site.

Collapse
 
paco_ita profile image
Francesco Leardini

If you mean to invalidate the cache, in the "activate" service worker lifecycle, you can delete all "other" service worker caches on the target client (the code snippet is in this article).

Otherwise, if you don't work with a service worker anymore and want to get rid of all the old, installed ones, you can refer to the new section the article: "How to get rid of 'zombie' service workers".

Collapse
 
martinrojas profile image
martin rojas

Thank you for adding that section. I had done some research and wanted to tweak your code a bit. Currenthing the registration.unregister() throws and error because registration is never defined. So this is what I have ended up using.

// Unregister the service worker
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.getRegistrations().then(function (registrations) {
    for (let registration of registrations) {
      //unregister service worker for old domain
      registration.unregister()
    }
  }).catch(function (err) {
    // fail state, which is fine as we just don't want a service worker.
    console.log('Fail: ', err);
  });
}

caches.keys()
    .then(keys =>
        Promise.all(keys.map(async key => await caches.delete(key))))
    .catch((err) => console.error('Something went wrong: ', err));

Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
paco_ita profile image
Francesco Leardini

Yeah, you need to invoke the code within the registration "scope", as you need it to invoke the unregister method.