Make your website work offline with service workers

In this tutorial I’m going to show you how to make your homepage available offline. To achieve this we will make use of Service Workers.

A service worker is a script that your browser runs in the background, separate from a web page, opening the door to features that don’t need a web page or user interaction.

Whilst we are concentrating on the Service Worker Cache Interface. Service workers can do other things such as:

How to debug

Service Workers only work with a valid SSL certificate. However, you can test locally by using the hostname http://localhost or

Registering a service worker

To register our service worker include the following javascript in your page:

if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/sw.js').then(function(registration) {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }, function(err) {
      // registration failed :(
      console.log('ServiceWorker registration failed: ', err);

Check it is working

in your console you should see:

you can also goto chrome://inspect/#service-workers in chrome to confirm.

Create our service worker

Create a new file called “sw.js” in the root of your site (referenced when registering our service worker):

var CACHE_NAME = 'example';
var urlsToCache = [

self.addEventListener('install', function(event) {
  // Perform install steps
      .then(function(cache) {
        console.log('Opened cache');
        return cache.addAll(urlsToCache);

self.addEventListener('fetch', function(event) {
      .then(function(response) {
        // Cache hit - return response
        if (response) {
          return response;
        return fetch(event.request);

self.addEventListener('activate', function(event) {
  var cacheWhitelist = ['example'];
    caches.keys().then(function(cacheNames) {
      return Promise.all( {
          if (cacheWhitelist.indexOf(cacheName) === -1) {
            return caches.delete(cacheName);

Here we are creating our cache with the command inside our install callback and telling it to cache the homepage(/).
Our fetch callback checks to see if we have hit the homepage and if we have a cached version. If so, it returns our cached page (cache hit).
Finally, the activate callback is used to detect any changes in our caches and update accordingly.

Checking the result

Visit your homepage, then, visit it again. You should see in chrome dev tools “from ServiceWorker

Now turn off your wifi or internet and view it again. Magic.

Insights by Trevor Sewell

Share this post