Service Worker Introduction

Step-by-step introduction to the Service Worker API.

Clear cache on activate

If our cached responses are outdated (for example our CSS changed), we can update our Service Worker and delete old caches on activation. Do make sure to exclude the new cache added on installation (just before the activation).

Code

// in sw.js
const currentCacheName = 'app-v2';
this.addEventListener('activate', event => {
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames
          .filter(cacheName => (cacheName.startsWith('app-')))
          .filter(cacheName => (cacheName !== currentCacheName))
          .map(cacheName => caches.delete(cacheName))
      );
    })
  );
});

Output

Reset all