Activate Service Workers Faster

By  on  

Service workers are great for many purposes:  speed, offline, cache control, and more.  You can view many code service worker usage samples over at the Service Worker Cookbook, if you're so interested.  One of those recipes, Immediate Claim, is as important and useful as it provides a way to claim your service worker more quickly, meaning you can receive fetch events faster.

You can liken the following code quickening to DOMContentLoaded (commonly known as domready) vs. the old load event -- set processing into motion more quickly.  The trick involves the service worker's install and activate events:

// Install event - cache files (...or not)
// Be sure to call skipWaiting()!
self.addEventListener('install', function(event) {
  event.waitUntil(
	caches.open('my-cache').then(function(cache) {
        // Important to `return` the promise here to have `skipWaiting()`
        // fire after the cache has been updated.
        return cache.addAll([/* file1.jpg, file2.png, ... */]);
    }).then(function() {
      // `skipWaiting()` forces the waiting ServiceWorker to become the
      // active ServiceWorker, triggering the `onactivate` event.
      // Together with `Clients.claim()` this allows a worker to take effect
      // immediately in the client(s).
      return self.skipWaiting();
    })
  );
});

// Activate event
// Be sure to call self.clients.claim()
self.addEventListener('activate', function(event) {
	// `claim()` sets this worker as the active worker for all clients that
	// match the workers scope and triggers an `oncontrollerchange` event for
	// the clients.
	return self.clients.claim();
});

Ultimately returning the skipWaiting() from the install event triggers the activate event, activating the service worker immediately and allowing your service worker to work with fetch events and other service worker capabilities.  Service workers require a navigation event (reloading the page, going to a new page, etc.) to activate which is why this trick is so handy.

Look forward to more service worker tips and examples on the blog over the coming months!

Recent Features

  • By
    Designing for Simplicity

    Before we get started, it's worth me spending a brief moment introducing myself to you. My name is Mark (or @integralist if Twitter happens to be your communication tool of choice) and I currently work for BBC News in London England as a principal engineer/tech...

  • By
    Serving Fonts from CDN

    For maximum performance, we all know we must put our assets on CDN (another domain).  Along with those assets are custom web fonts.  Unfortunately custom web fonts via CDN (or any cross-domain font request) don't work in Firefox or Internet Explorer (correctly so, by spec) though...

Incredible Demos

  • By
    Create Twitter-Style Dropdowns Using jQuery

    Twitter does some great stuff with JavaScript. What I really appreciate about what they do is that there aren't any epic JS functionalities -- they're all simple touches. One of those simple touches is the "Login" dropdown on their homepage. I've taken...

  • By
    Full Width Textareas

    Working with textarea widths can be painful if you want the textarea to span 100% width.  Why painful?  Because if the textarea's containing element has padding, your "width:100%" textarea will likely stretch outside of the parent container -- a frustrating prospect to say the least.  Luckily...

Discussion

  1. Şafak Gür

    MDN samples always use event.waitUntil on activate. Does returning a promise like you did does the same?

    • Paul

      No – using waitUntil() just means all the items have been cached before the service worker is activated. Using skipWaiting() means that you don’t have to do a second re-load of the site to actually activate the service worker. The second reload for me is the only annoying thing about service workers. It’s amazing how much searching of the internet I had to do to find out how to overwrite the default behaviour.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!