Service Workers: Using SW-Toolbox to Serve an Offline Page

If you’re using a browser with Service Worker support, you can turn off your internet connection and try to visit a new page from this site. Instead of the default browser offline page, you’ll get a friendlier custom page.

Thanks to Jeff Posnick and his solution to this Github issue. Here’s how to make it work with an example of how your Service Worker file could be setup:

Service Worker: sw.js

self.importScripts('assets/sw-toolbox/sw-toolbox.js');

self.toolbox.precache([
  '/offline',
  '/images/you-are-offline.svg',
  // ...
]);

self.toolbox.router.get('/(.*)', function(req, vals, opts) {
  return toolbox.networkFirst(req, vals, opts)
    .catch(function(error) {
      if (req.method === 'GET' && req.headers.get('accept').includes('text/html')) {
        return toolbox.cacheOnly(new Request('/offline'), vals, opts);
      }
      throw error;
    });
});

We first import SW-Toolbox, then add files and assets that should be precached. In there we make sure to precache our offline page and any assets that would be needed by that page.

We then call SW-Toolbox’s toolbox.router.get with a callback to toolbox.networkFirst, but with a twist. If both the network and the cache fail to provide a response, the promise will fail. We can then use catch on the promise to request our offline page.

You could also have some of your most popular pages precached and link to them from your custom offline page. This way your visitors can still get some value while they’re offline. That’s a strategy that Smashing Magazine has been using for example.

Boom, a nice offline page 😀

The Alligator.io offline page

Search

🔎 Searching...