Skip to main content

Offline Cache with Service Workers

A basic overview of how to use a Service Worker to provide an offline cache for your Progressive Web App

Service Workers are a type of JavaScript Worker which can do a whole bunch of things to give Progressive Web Apps a true app-like feel. Even though they offer much more, this short article will focus on the offline cache. You may have used the HTML Application Cache in the past, Service Workers fix a lot of it's problems.

Bare bones example

// Register the service worker in your page
navigator.serviceWorker.register('sw.js');

Just like a regular JavaScript Worker, the Service Worker code is in a separate file.

Contents of sw.js

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open('PREFETCH_CACHE').then(function(cache) {
      return cache.addAll([
        '/',
        '/css/site.css',
        '/js/site.js'
      ]);
    })
  );
});

// This event is fires for all "in-scope" requests
self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request).then(function(response) {
      // If we have a cache hit then return the response else fetch from the network
      return response || fetch(event.request);
    })
  );
});

When the Service Worker is first registered, or it decides that sw.js has changed (by performing a byte for byte comparison) it will raise an install event. The code above adds all the files to be "prefetched" to the cache.

Service Workers are network proxies and they allow you to intercept requests from your page and decide how to handle them. Because we're interested in caching, we intercept all requests by listening for the fetch event and return a response from the cache if we match it, otherwise we hit the network.

Due to it's asynchronous nature, the Service Worker API makes heavy use of JavaScript Promises.

Additional reading

Hello, my name is Lee and I work as a full-stack web developer specialising in Microsoft ASP.NET technologies. I love using Umbraco and also MANAGED, my own application management software.

Contact me at lee.gunn@secretorange.co.uk

All skills

Contact

Get in touch to talk about your project or just ask me a question.

lee.gunn@secretorange.co.uk