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.

Note: Service workers on their own cannot cache AJAX requests. I’ll talk about solutions for caching API requests in a later blog post.

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) {

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() {'cash').then(function(cache) {

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

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?

Questions? Tweet me!