What a service worker actually does

A service worker is a JavaScript file that sits between your site and the network, acting as middleware: every request the site makes and every response it receives passes through the worker first. The worker also has its own cache where responses and assets can be stored locally.

Those two capabilities cover a lot of ground:

  • Frequently used assets can be served from cache instead of the network, cutting data usage and improving performance.
  • Critical content — or a whole site or app — can remain available when the visitor is offline.
  • Assets and API responses can be prefetched so they're ready before the user asks for them.
  • Fallback assets can be returned in place of HTTP errors.

Service workers differ from ordinary scripts in several ways. They have no DOM access, they run on their own thread so they don't block other JavaScript, and they are fully asynchronous by design.

Security and placement constraints

Because a service worker sees every request and response for your site, the browser restricts where it can live.

  • Same-origin only. You cannot serve a service worker from a CDN or other third party; it must be hosted on the domain where it runs.
  • SSL required. Service workers only run on sites with an installed certificate. Many hosts supply one free or cheaply, and Let's Encrypt offers one at no cost for command-line users. localhost testing is exempt, but the file:// protocol is not supported — you need a local server.

Scope is also tied to location: a service worker only controls the directory it sits in and that directory's subdirectories. A file at /js/sw.js governs /js only, so the worker belongs in your site's root.

Registering the worker

Before anything else the browser must be told about the worker. Call navigator.serviceWorker.register() with the path to the worker file.

navigator.serviceWorker.register('sw.js');

Registration can run from an external script, but running it inline in the HTML executes it as early as possible. Since support is broad but not universal, guard the call with a feature check.

if (navigator && navigator.serviceWorker) {
  navigator.serviceWorker.register('sw.js');
}

After the worker installs, the browser must activate it. Activation typically occurs only when no worker is currently active, or when the user refreshes the page. Until that point the worker neither runs nor intercepts requests.

Intercepting requests

Once active, the worker catches every request through the fetch event, attached with self.addEventListener(). Inside the handler, the request object is available as event.request.

// Listen for request events
self.addEventListener('fetch', function (event) {
  // Do stuff...
});

Some Chromium versions throw an error here when a page is opened in a new tab. Paul Irish's fix is small enough to include in every worker as a precaution:

// Listen for request events
self.addEventListener('fetch', function (event) {

  // Get the request
  let request = event.request;

  // Bug fix
  // https://stackoverflow.com/a/49719964
  if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') return;

});

Choosing a request strategy

Two primary strategies exist, and most sites combine them by asset type.

  1. Network-first. The request goes to the network; if it fails or there is no connectivity, the worker looks in its cache.
  2. Offline-first. The cache is checked first; if there's no match, the request goes to the network.

Offline-first suits large, stable assets such as CSS, JavaScript, images and fonts. Network-first fits assets that change often, like HTML and API responses.

Assets generally reach the cache in one of two ways:

  1. Pre-cache on install. Core files used on nearly every page — CSS, JavaScript, logo, favicon, fonts — are cached during the install event and then served offline-first.
  2. Cache as you browse. Assets that only some visitors touch, such as blog posts and article images, are cached in real time as they're requested, then served by default or as a fallback.

Implementing the strategies

Inside the fetch handler, request.headers.get('Accept') returns the MIME type of the content, which lets you branch on file type with String.includes() — HTML, for example, is text/html. MDN maintains a list of common types.

// Listen for request events
self.addEventListener('fetch', function (event) {

  // Get the request
  let request = event.request;

  // Bug fix
  // https://stackoverflow.com/a/49719964
  if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') return;

  // HTML files
  // Network-first
  if (request.headers.get('Accept').includes('text/html')) {
    // Handle HTML files...
    return;
  }

  // CSS & JavaScript
  // Offline-first
  if (request.headers.get('Accept').includes('text/css') || request.headers.get('Accept').includes('text/javascript')) {
    // Handle CSS and JavaScript files...
    return;
  }

  // Images
  // Offline-first
  if (request.headers.get('Accept').includes('image')) {
    // Handle images...
  }

});

Within each branch, event.respondWith() replaces the response sent back to the browser.

Network-first

Pass the request to fetch() and return the successful response — the same result as having no worker at all. When the network fails, Promise.catch() takes over, and caches.match() can locate the page in cache and return it instead of the browser's default error.

// Send the request to the network first
// If it's not found, look in the cache
event.respondWith(
  fetch(request).then(function (response) {
    return response;
  }).catch(function (error) {
    return caches.match(request).then(function (response) {
      return response;
    });
  })
);

Offline-first

Query the cache first with caches.match() and return any hit. On a miss, fall through to fetch().

// Check the cache first
// If it's not found, send the request to the network
event.respondWith(
  caches.match(request).then(function (response) {
    return response || fetch(request).then(function (response) {
      return response;
    });
  })
);

Populating the cache at install time

In an install listener, caches.open() takes a cache name — app here — and returns a Promise: it resolves with an existing cache of that name, or creates one and resolves. The cache is scoped to your domain; other origins can't reach it, and a same-named cache elsewhere stays entirely separate.

// Listen for the install event
self.addEventListener('install', function (event) {
  event.waitUntil(caches.open('app'));
});
// Listen for the install event
self.addEventListener('install', function (event) {

  // Cache the offline.html page
  event.waitUntil(caches.open('app').then(function (cache) {
    cache.add(new Request('offline.html'));
    return cache;
  }));

});

Chaining then() onto caches.open() gives you the cache to work with. Files are added by constructing a new Request() for each and calling cache.add(), then returning the cache. Wrapping the work in event.waitUntil() holds the install event open until caching finishes. A practical pattern is an array of core file paths, looped over after the cache opens.

let coreAssets = [
  '/css/main.css',
  '/js/main.js',
  '/img/logo.svg',
  '/img/favicon.ico'
];

// On install, cache some stuff
self.addEventListener('install', function (event) {

  // Cache core assets
  event.waitUntil(caches.open('app').then(function (cache) {
    for (let asset of coreAssets) {
      cache.add(new Request(asset));
    }
    return cache;
  }));

});

Caching during browsing

For on-demand assets, clone the successful network response with Response.clone(). Open the cache with caches.open(), then store the copy using cache.put(), passing the request and the copy. event.waitUntil() keeps the event alive until the write completes, after which the original response is returned as usual. cache.put() is the right call here rather than cache.add(), since we already hold a response and cache.add() would trigger a second network request.

// HTML files
// Network-first
if (request.headers.get('Accept').includes('text/html')) {
  event.respondWith(
    fetch(request).then(function (response) {

      // Create a copy of the response and save it to the cache
      let copy = response.clone();
      event.waitUntil(caches.open('app').then(function (cache) {
        return cache.put(request, copy);
      }));

      // Return the response
      return response;

  }).catch(function (error) {
      return caches.match(request).then(function (response) {
        return response;
      });
    })
  );
}

Putting it to work

A copy-paste boilerplate is available on GitHub: add your core assets to the coreAssets array and register the worker to get started. Beyond that baseline, the same mechanisms support advanced API caching strategies, a dedicated offline page with critical information, and cleanup of caches that grow too large as the user browses.

For further reading, Jeremy Keith's Going Offline is a solid primer on service workers, and Jason Grigsby's book on progressive web apps goes deeper into the available strategies.