Overwhelmed by service workers? Here’s a collection of tools and libraries that will help tame this powerful beast!
sw-precache
Offline-first, fast, with the sw-precache module is the tagline of the Google-built sw-precache library. It’s a module that integrates with your gulp or Grunt build process: sw-precache will generate a list of versioned resources for you, as well as a service worker that will cache and serve these resources.
If you’re using gulp or Grunt, then sw-precache is a no-brainer! But even if you’re not, there’s a command line interface for sw-precache that you can use instead.
sw-precache example usage
The gulp task code below will generate a service worker that caches all images, JavaScript, HTML and CSS files.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
gulp.task('generate-service-worker', function(callback) { var fs = require('fs'); var path = require('path'); var swPrecache = require('sw-precache'); var rootDir = 'app'; swPrecache({ staticFileGlobs: [rootDir + '/**/*.{js,html,css,png,jpg,gif}'], stripPrefix: rootDir }, function(error, swFileContents) { if (error) { return callback(error); } fs.writeFile(path.join(rootDir, 'service-worker.js'), swFileContents, callback); }); }); |
You now have a gulp task that you can run with:
$ gulp generate-service-worker
If you don’t use gulp or Grunt, you can use the command line interface. To cache just HTML files, for example, you would use:
$ sw-precache –root=dist –static-file-globs=’dist/*/.html’
sw-toolbox
The Service Worker Toolbox, also known as sw-toolbox, is another library from Google that offers a variety of wrappers for simplifying the most common service worker tasks such as:
- Service worker registration
- URL request routing and routing patterns
- Bult-in network strategy/caching request handlers: The most common network strategies are available as built-in request handlers, and include
toolbox.networkFirst
toolbox.cacheFirst
toolbox.fastest
toolbox.cacheOnly
toolbox.networkOnly
- Precaching
These are all powerful features, but can be tricky to implement correctly by hand.
sw-toolbox example usage
To include the toolbox in your service worker, simply use importScript:
1 |
importScripts('sw-toolbox/sw-toolbox.js'); |
You can register service workers in the usual way, or with an HTML include:
1 |
<script src="/path/to/sw-toolbox/companion.js" data-service-worker="my-service-worker.js"></script> |
There is strong support for routing, the mapping of URL requests and methods to handlers. The example below shows basic routing, with a URL being mapped to the built-in toolbox.networkFirst
handler.
1 |
toolbox.router.get('/myapp/index.html', toolbox.networkFirst); |
Regular expression routes, and Express-style routes are also supported. For example, an Express-style route might look something like this, with :foo
being auto-populated in the handler:
1 2 3 4 |
toolbox.router.get(':foo/index.html', function(request, values) { return new Response('Handled a request for ' + request.url + ', where foo is "' + values.foo + '"'); }); |
Polymer platinum-sw
The Polymer library has a set of elements, the platinum elements, which help turn your web page into a true webapp. The platinum-sw bundle contains service worker helper elements which abstract common service worker tasks.
The bundled elements are:
platinum-sw-import-script
: used to import a JavaScript file that is executed each time the service worker starts up.platinum-sw-fetch
: creates custom fetch event handlers for given URL patterns to intercept network requests and provide custom response handlingplatinum-sw-cache
: can precache specific resources, perform runtime caching, and serve your cached resources when a network is unavailable.platinum-sw-offline-analytics
: intercepts Google Analytics pings, so that analytics data can be collected even when offline. Data will be sent to Google when a network connection becomes availableplatinum-sw-register
: registers a service worker, handling various options, such asskip-waiting
andclients-claim
platinum-sw example usage
Polymer code to show how to register and set up a custom fetch handler might look like this. Note that promise handling with respect to registration options is managed for you:
1 2 3 4 5 6 7 |
<platinum-sw-register skip-waiting clients-claim auto-register> <platinum-sw-import-script href="custom-fetch-handler.js"></platinum-sw-import-script> <platinum-sw-fetch handler="customFetchHandler" path="/(.*)/customFetch"></platinum-sw-fetch> </platinum-sw-register> |
The Polymer service worker elements are built on top of the sw-toolbox library mentioned earlier.
The Service Worker Cookbook
Not a library as such, Mozilla’s Service Worker Cookbook is a collection of service worker recipes, organised by difficulty level (Beginner, Intermediate, and Advanced), and category (General, Offline, Beyond Offline, Performance, and Web Push). Each recipe contains a live demo, code for the webpage (index.js
), code for the service worker (service-worker.js
), and, if needed, code for the server (server.js
).
Recipes include some of the most common service worker use cases, such as caching and offline patterns, as well as several web push notification patterns, an API analytics, and load balancer demos.
UpUp
UpUp is an open source project that builds on service workers to provide an easy-to-use API for providing offline content. UpUp detects when the network is not available, and delivers offline content instead. To use it, you need to add its two files to your website, upup.min.js
and upup.sw.min.js
. Then all that’s left is to declare which resources should be available offline.
UpUp example usage
After adding the two files mentioned above, you need to specify what resources should be available offline, using the UpUp.start
method. The most simple use case is to show a simple offline page, instead the browser’s default offline page:
1 2 3 4 5 6 7 |
<script src="/upup.min.js"></script> <script> UpUp.start({ 'content-url': 'offline.html', 'assets': ['/img/logo.png', '/css/style.css'] }); </script> |
As the library’s developer points out, there is nothing stopping you from developing rich offline experiences, even tailored for individual users, or making use of a framework to deliver its experience:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<script src="/upup.min.js"></script> <script> UpUp.start({ 'content-url': 'schedule.html?user=joe', // show this when the user is offline 'assets': [ // define additional assets needed while offline: 'img/logo.png', // such as images, 'css/offline.css', // custom stylesheets, 'schedule.json?user=joe', // dynamic requests with data per user, 'js/angular.min.js', // javascript libraries and frameworks, 'mov/intro.mp4', // videos, 'contacts.pdf' // and more. ] }); </script> |
Offline Plugin for webpack
This plugin integrates with webpack to provide offline experiences using service workers with appcache fallback. It provides a rich set of configuration options to tweak what should be cached, how things should be cached, as well as scoping, and cache invalidation strategies.
Offline plugin for webpack example usage
To use this plugin, you first instantiate and set some options in your webpack.config
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
var OfflinePlugin = require('offline-plugin'); module.exports = { // ... plugins: [ // ... other plugins new OfflinePlugin({ // All options are optional caches: 'all', scope: '/', updateStrategy: 'all', version: 'v1', ServiceWorker: { output: 'sw.js' }, AppCache: { directory: 'appcache/' } }) ] // ... } |
Then you include and install in your client script with the following:
1 |
require('offline-plugin/runtime').install(); |
If you know of a library or service that we’ve left out, let us know and we’ll add it!
Leave a Reply