Service Worker Introduction

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

Serve from cache

When a request is already cached (eg. during install) we can serve it directly. If the response is not cached, we can fetch it like the browser normally would.

With this setup we can render our page even when we are offline. Try it (turn off network / shut down server).

Code

// in sw.js
this.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(response => {
      	return response || fetch(event.request)
      })
  );
});

The caches.match accepts additional options to refine matching.

The service worker intercepts requests before they reach the browser and server cache.

When you serve content from the cache you are also responsible for invalidating the cache.

Output

Reset all