sw-toolbox – A Collection of Tools for Service Workers

Service Worker Toolbox provides some simple helpers for use in creating your own service workers. Specifically, it provides common caching strategies for dynamic content, such as API calls, third-party resources, and large or infrequently used local resources that you don’t want precached.

The code itself is very readable I must say:

importScripts('sw-toolbox.js');

toolbox.precache([
  '/css/app.css',
  '/img/logo.png'
]);

toolbox.router.get('/css*', toolbox.cacheFirst);
toolbox.router.get('/img*', toolbox.cacheFirst);
toolbox.router.get('/(.*)', toolbox.networkFirst, { networkTimeoutSeconds: 5});

A bit more advanced is to precache a “you’re offline” page first, and return that in case a user is offline (src):

importScripts('sw-toolbox.js');

toolbox.precache([
  '/offline',
  '/img/offline.png',
   // …
]);

// …

toolbox.router.get('/(.*)', function(request, values, options) {
  // networkFirst will attempt to return a response from the network,
  // then attempt to return a response from the cache.
  return toolbox.networkFirst(request, values, options).catch(function(error) {
    // If both the network and the cache fail, then `.catch()` will be triggered,
    // and we get a chance to respond with our cached fallback page.
    if (request.method === 'GET' && request.headers.get('accept').includes('text/html')) {
      return toolbox.cacheOnly(new Request('/offline'), values, options);
    }
    throw error;
  });
});

sw-toolbox
sw-toolbox (GitHub) →

A beginner’s guide to making Progressive Web Apps forms a nice introduction to implementing Service Workers using sw-toolbox.

If you’re looking for a non-library version I’d recommend starting with Implementing “Save For Offline” with Service Workers.

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.