Skip to content
Mobileintermediate

What is a service worker?

Updated Nov 30, 20263 min readBased on official documentation
What is a service worker?

In short

A service worker is a JavaScript file that runs in the background, separate from your web page. It sits between your site and the network, so it can intercept requests, cache files, and let your app keep working when the connection drops. It only runs on secure pages served over HTTPS, or on localhost during development.

A service worker is a small script that a browser runs for your website. The page itself does not run it. The browser runs it on a separate thread, so it does not slow down the page. Because it sits between the page and the network, it can decide what to load, where to load it from, and what to store for later.

How it works

You register a service worker from your main page with the register method on the service worker container. If the registration succeeds, the browser downloads the file and tries to install it. The worker then controls the pages in its scope, which is the part of the site you choose, or the whole origin by default.

A service worker goes through a simple lifecycle. First the browser downloads it. Then it installs. Finally it activates. The install event is the place to prepare things, such as creating a cache and saving the files your app needs offline. The activate event is a good time to remove caches left over from an older version.

When you update the worker file, the browser compares it byte by byte with the old one. If it has changed, the new version installs in the background but waits. It only takes over once no open pages still use the old version. You can change this behaviour in code if you want the new version to take over sooner.

Once active, the worker listens for fetch events. Each time the page asks for a resource, such as a script, an image or an API response, the worker receives a fetch event. It can answer from the cache, go to the network, or combine both. This is what lets an app load even when there is no connection.

When to use it

Service workers fit tasks that need to run around the page rather than inside it. Common uses include offline support, faster repeat visits through caching, and fetching data in the background. The documentation also lists ideas such as pre-fetching the next few images in a photo gallery and mocking APIs during development.

They are less suited to tasks that need direct access to the page. A service worker has no access to the DOM, which is the tree of elements that makes up a web page. It also cannot use synchronous XHR or Web Storage, so it works with asynchronous calls and promises instead. It cannot dynamically import modules with import(), though static import statements work.

A simple example

The snippet below shows the typical shape of a worker that caches a few files during install and serves them when the network is missing. It is a sketch, not a complete app.

const CACHE = "app-v1";

self.addEventListener("install", (event) => {
  event.waitUntil(
    caches.open(CACHE).then((cache) =>
      cache.addAll(["/", "/styles.css", "/app.js"])
    )
  );
});

self.addEventListener("fetch", (event) => {
  event.respondWith(
    caches.match(event.request).then((hit) => hit || fetch(event.request))
  );
});

The waitUntil call tells the browser to keep the install event open until the files are saved. Without it, the browser could move on before the cache is ready.

Common mistakes

The most common mistake is forgetting that service workers need a secure context. Your site must use HTTPS, with http://localhost as the exception for development. Firefox offers a setting to test over plain HTTP, but that is only for testing.

Another mistake is assuming a new version takes effect right away. The old worker keeps running until all pages using it are closed. Plan your cache names with versions, and clean up old caches in the activate event, so you do not serve stale files forever.

A third mistake is expecting the worker to behave like page code. It runs in a separate context with no window object. Keep heavy logic out of the fetch handler when you can, because the browser may need to start the worker before it can answer a request, which adds a small delay.

Alternatives

Before service workers, many sites used AppCache. The documentation notes that AppCache made assumptions that often broke in practice. Service workers give finer control, since you decide which requests to cache and how to answer them. For simple offline pages, you may not need a service worker at all. For data stored on the client, you might look at other browser storage options instead.

FAQ

Can a service worker access the DOM?

No. A service worker runs in a worker context with no DOM access. It communicates with your page through messages and events instead.

Why does my service worker only run on HTTPS?

Service workers are only available in secure contexts, so the page must be served over HTTPS. Browsers make an exception for localhost to make local development easier.

When does a new service worker take control?

A new version installs in the background and waits. It activates once no open pages still use the old version, unless the code calls skipWaiting to activate sooner.

Do I need a service worker to make my site work offline?

Not always, but it is the main browser tool for offline support. It lets you decide which files to cache and how to respond when the network is missing.

Sources

This page is based on the official documentation below. Read it for full detail.

Service Worker — official documentation ↗
blozhikDeveloper news from across the web, explained. Every story links to its original sources.