Service Worker Introduction

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

Cache on install

For an offline first approach, the install phase is ideal to fetch and cache a main (catch all) page and static assets, to be used when offline.

Code

// in sw.js
this.addEventListener('install', event => {
  event.waitUntil(
    caches.open('app-name-v1').then(cache => {
      return cache.addAll([
        './',
        '../assets/app.css',
        '../assets/app.js'
      ]);
    })
  );
});

Caches are shared across the origin, so it's important to give them a distinctive name. See also clear cache on activate.

The cache.addAll method stores the Responses by Request in the CacheStorage, so we can use these later.

You can view the CacheStorage via Developer Tools > Resources > Cache Storage.

Output


Reset all