Service Worker Introduction

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

Cache on fetch

If no match is found in the cache, we can perform the fetch and store the response in the cache. This way, it will be available from cache the next time it's requested.

Code

// in sw.js
this.addEventListener('fetch', event => event.respondWith(
  caches.match(event.request).then(response => {
    return response || fetch(event.request).then(response => {
      return caches.open('app-v1').then(cache => {
        cache.put(event.request, response.clone());
        return response;
      });
    });
  })
});

Note that we need to clone the response because the response (and request) body can only be consumed once.

Output

Reset all