Skip to content

Republic / Articles /

Article updated 2025-02-05.
Written by Christofer Sandin.

Adding Functionality with Service Workers

W3C has written a specification called Service Workers. It is a way to run scripts in the browser in a new manner. This means, among other things, that the Service Workers running do not have access to the DOM and must stand on their own. It can be a bit tricky to understand what this entails, but hang on, and we’ll take a look at it.

Service Workers extensively use a new feature in JavaScript called Promises, which can be a bit confusing if you haven't worked with it before. There are many people who know more about this and explain it better than I do. I can recommend the article “JavaScript Promises - There and back again” on Google's project html5rocks.com, as well as the article “ES6 Promises in Depth” on Pony Foo. If you haven’t heard of Promises before, start there...

To use a Service Worker, you must run over https, but you can also test your workers on http://localhost.

Browser Support

As of today, when this article is written, Service Workers are supported in the latest versions of Chrome and Opera. Hopefully, other browsers will follow suit as soon as possible.

The good thing is that the functionality built using Service Workers adds enhancements and additions to the already functioning website or web service, so it’s perfectly fine that it doesn’t work everywhere right away.

You can start benefiting from Service Workers now; those that support the features will gain from them while those that do not yet can use the website just as before.

An updated overview of how things look can be found at Is Service Worker ready?.

Inspecting All Installed Service Workers

Curious about which Service Workers are installed and running?

In Chrome, you can type chrome://inspect/#service-workers in the address bar to bring up a list of the scripts that are running; you can inspect these and remove the ones you don’t want. If you’re developing in Opera, you should use browser://serviceworker-internals instead.

You can also find these in the regular Dev Tools (under Resources) in Chrome Canary and Opera Beta, indicating that this is where they will land in the regular versions in the future as well.

Different Design Patterns for Service Workers

Jake Archibald at Google Chrome has put together a page with "recipes" for small design patterns that you can use when writing code for Service Workers.

It can be helpful to read through these as they are often used by those writing about Service Workers.

A First Example

In the article “My first Service Worker”, Jeremy Keith describes his first script that runs as a Service Worker. It’s an easy-to-read and good example to start with if you’re interested. Jeremy's serviceworkers.js is also published as a Gist on Github under Public Domain license if you want a working example to start with.