If you want to learn everything you need to know about service workers, head over to serviceworkerbook.com and order my book, “Let’s Take This Offline”! Be sure to use first-serviceworker for 10% off!

Note: This is a pretty old post, which didn’t include the most fully-featured version of a beginner service worker. If you’re looking for a better getting started post, I recommend checking out this post.

Service Workers are a super cool bit of tech that allows your user’s browser to cache files and assets. Why is this so cool? Because eventually your user will lose connection. What happens then? Without something to bridge the gap between the time user loses connection and the time they regain connection, your user is just out of luck.

But no more! Service workers are here to help bridge the gap (at least in certain browsers). With the browser caching the files and images you choose, your user can continue using your site until the connection comes back.

To start using a service worker you’ll need some JavaScript for your application, as well a service worker file. I’ve created a demo Let’s get started!

Step One: Register your service worker

Registering your service work is very simple. The code looks like this:


if(navigator.serviceWorker) {
  navigator.serviceWorker.register('service-worker.js');
}

The above code would go in your application’s JavaScript file. All it’s doing is letting the browser know to go ahead and register that service worker. Be sure to wrap your register function in an if-statement because cross-browser support for service workers isn’t quite there yet.

Step Two: Install your service worker

This code lives in your service-worker.js file:


// service worker
self.oninstall = function() {
  caches.open('cash').then(function(cache) {
    cache.addAll([
      'index.html',
      '/img/my-image-name.jpg'
    ]);
  });
};

Service workers expose certain events, including oninstall and fetch. The method above opens a cache in the browser and adds files to the cache. This way, if your app goes offline, the browser already has files and can load them in. Another benefit of this is speeding up your site’s response time. Since the files are cached, the browser no longer needs to serve files from a remote server. This ends up giving your users a great performance increase.

Step Three: Specify what happens on fetch

This code also lives in your service-worker.js file:


// fetch function
// called when connection is lost
self.onfetch = function(event) {
  // this will grab the very last request
  event.respondWith(caches.match(event.request));
};

Note: This step was not a part of the original post.

Step Four: Handle for requests that aren’t in your cache:


// fetch function
// called when connection is lost
self.onfetch = function(event) {
  // this will grab the very last request
  event.respondWith(
    caches.match(event.request)
    .then(function(cachedFiles) {
      if(cachedFiles) {
        return cachedFiles;
      } else {
        fetch(event.request);
      }
    })
  );
};

This is the function that will be called when your files need to be fetched. When files are cached, they are saved like a stack. Older caches are closer to the bottom, with newest caches being on top. The above function will grab the latest cache and send that to the browser where it can be rendered.

And with that, you’re done! You can grab this code and run it in a server (I like to use https-server). Once you stop the server, you can refresh the page and see your site is still there! Pretty cool, huh?

Thanks so much for reading! If you liked this post, you should head on over to serviceworkerbook.com and buy my book! Be sure to use first-serviceworker for 10% off!