HTTP, TLS & Web Performance

Service Workers and Offline-Capable Sites

See how a service worker intercepts requests, which caching strategy fits each resource, and how to ship updates without trapping visitors.

Key takeaways

  • A service worker runs separately from the page, handles network requests for its scope and has no direct access to the DOM.
  • It requires a secure context, which means HTTPS, with localhost allowed for development.
  • Different resources need different strategies, such as cache first for versioned assets and network first for pages.
  • A new worker normally waits until pages controlled by the old one are closed.
  • Browsers can evict stored data, so offline copies are a convenience and not a backup.

A service worker is a script your website installs in the visitor's browser that can sit between your pages and the network. When a page asks for something, the worker can answer from its own storage, go to the network, or combine the two. That's what lets a site open without a connection and load instantly on repeat visits.

It's powerful enough to cause trouble. A careless worker can keep serving an old version long after you've fixed it, so plan updates before you write the first cache.

What it can and can't do

A service worker runs in the background, on its own thread, and isn't tied to one tab. It communicates with pages by passing messages. It can't touch the page's elements or use synchronous storage such as localStorage. It uses promises, the Cache API for request and response pairs, and IndexedDB for structured data.

The browser starts it when there's an event to handle and stops it when idle. Never keep anything important only in its variables.

Beyond offline support, workers enable push notifications and, in some browsers, background synchronization. They're one of the building blocks of progressive web apps.

The idea in one picture

Without a worker, every request goes from the page to the ordinary browser cache and then to the network. With one, your code gets the first say.

A cached page opening with no connection
Page Service worker Network Request an article 1 Try the network first 2 Fails: device is offline 3 Return the stored copy or offline page 4 Page Service worker Network Request an article 1 Try the network first 2 Fails: device is offline 3 Return the stored copy or offline page 4

Because the worker is ordinary code, you decide what happens at each step. That freedom is the difference from HTTP caching, where headers describe a policy and the browser carries it out.

HTTPS is required because a script that can rewrite every response would be very dangerous if someone on the network could inject it. For the same reason, treat the worker file with care: a cross-site scripting flaw or a compromised build that changes it can affect visitors long after the original problem is gone.

Registration and scope

A page registers the worker:

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js');
  });
}

Registering after load avoids competing with the first view for bandwidth.

The scope is the set of pages the worker controls. By default it's the directory containing the script, so /sw.js can control the whole origin, while /app/sw.js controls pages under /app/. A server can widen the allowed scope with the Service-Worker-Allowed header, but placing the file correctly is simpler.

The lifecycle

From registration to control
1 Register A page tells the browser about the script. 2 Install The worker can pre-cache essential files. 3 Wait A new version waits if an old one is in use. 4 Activate Old caches can be cleaned up. 5 Handle requests Fetch events arrive for pages in scope. Register A page tells the browser about the script. 1 Install The worker can pre-cache essential files. 2 Wait A new version waits if an old one is in use. 3 Activate Old caches can be cleaned up. 4 Handle requests Fetch events arrive for pages in scope. 5

On a first visit, the page that registered the worker isn't controlled until it's reloaded, unless the worker calls clients.claim().

A small working example

This worker stores an offline page and shows it when a navigation fails:

const CACHE = 'site-v3';

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE).then((c) => c.addAll(['/offline.html', '/css/offline.css']))
  );
});

self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then((names) =>
      Promise.all(names.filter((n) => n !== CACHE).map((n) => caches.delete(n)))
    )
  );
});

self.addEventListener('fetch', (event) => {
  const request = event.request;
  if (request.mode === 'navigate') {
    event.respondWith(fetch(request).catch(() => caches.match('/offline.html')));
  } else if (request.method === 'GET') {
    event.respondWith(caches.match(request).then((hit) => hit || fetch(request)));
  }
});

addAll fails as a whole if any file can't be fetched, and then installation fails. Keep the list short. The cleanup step deletes every other cache on the origin, so if something else on your site uses the Cache API, filter by your own prefix.

Choosing a strategy per resource

Strategy Behavior Suits
Cache first Use the stored copy, else network Versioned scripts, styles, fonts
Network first Try network, fall back to cache Articles and other HTML
Stale while revalidate Answer from cache, refresh behind Avatars, non-critical lists
Network only Never cache Payments, sign-in, live data
Cache only Only what was pre-stored Offline fallback assets
Matching a strategy to freshness needs
Never changes Cache first. Hashed assets are ideal. Changes, staleness is fine Serve stored copy and refresh in background. Changes, freshness matters Network first with a cached fallback. Private or transactional Go to the network and store nothing. Never changes Cache first. Hashed assets are ideal. Changes, staleness is fine Serve stored copy and refresh in background. Changes, freshness matters Network first with a cached fallback. Private or transactional Go to the network and store nothing.

Check responses before storing them. Caching a 404 or an error page as though it were content produces confusing bugs. Remember too that a request made by your worker still passes through the ordinary HTTP cache, so your Cache-Control headers continue to matter.

Deciding what to pre-cache

Pre-caching downloads files during installation, before anyone asks for them. It guarantees they're available offline, and it also spends the visitor's data on things they may never use. Keep it to the application shell: the offline page, the main stylesheet, essential scripts, a logo and perhaps a font.

Cache everything else as it's used. For a news or documentation site, storing the last few pages someone opened is often more useful than guessing. Some sites add a "save for offline" button, which makes the choice explicit and sets expectations.

Put a ceiling on runtime caches. The Cache API doesn't expire entries on its own and ignores freshness headers when you match against it, so your code has to delete old items, by count or by age. Libraries such as Workbox provide strategies and expiry rules ready-made, which saves writing and debugging them yourself. Understand what the library does before shipping it, because the consequences of a wrong rule are the same.

Name caches by purpose and version, such as one for the shell and one for pages, so that a release can replace one without discarding the other.

Updating safely

The browser checks for a new worker script on navigation to a page in scope, among other times. If the bytes differ, it installs the new one, which then waits while any tab still uses the old one. A simple reload may not be enough, because the old page is still alive while the new request is made.

You can force the change with self.skipWaiting() during install, combined with clients.claim(). The risk is that an already open page, built for the old version, suddenly receives new assets or finds its cache deleted. A friendlier approach shows a "new version available" notice and lets the visitor choose to reload.

Don't give the worker script a long cache lifetime, and never rename it with a hash on each release. Keep one stable address, served with Cache-Control: no-cache. The general principles are in cache invalidation.

An escape hatch

If a faulty worker is in the wild, deploy a replacement at the same address that removes itself:

self.addEventListener('install', () => self.skipWaiting());
self.addEventListener('activate', (event) => {
  event.waitUntil(self.registration.unregister());
});

It has no fetch handler, so pages go back to the network. Add cache deletion if stored files are also wrong. Simply deleting the script from the server is slower and less predictable.

Offline writes and storage limits

Reading offline is the easy part. Letting people submit forms or edit data offline means saving the changes in IndexedDB, showing clearly that they're pending, sending them when the connection returns, and handling conflicts. Give each queued operation a unique identifier so a repeated send doesn't create duplicates.

Storage isn't guaranteed. Browsers set quotas, may evict data when space runs low or after long disuse, and users can clear it. Limit how much you keep, remove old entries, and avoid storing sensitive personal data on devices that may be shared. Clear it on sign-out.

What can go wrong

  • Visitors stuck on old content. Usually cache-first HTML. Use network first for pages.
  • A worker that breaks everything. Test the failure paths and keep the removal script ready.
  • Development confusion. Your developer tools have an Application or Storage panel to inspect workers, bypass them and clear caches.
  • Opaque responses. Cross-origin files fetched without CORS can't be inspected and may count heavily against quota. See CORS explained.
  • Flaky networks. A network-first request can hang for a long time. Add a timeout that falls back to the cache.

Testing before release

Test as visitors experience it. Load the site, go offline using the developer tools or airplane mode, and browse. Then deploy a changed version and confirm how an already open tab, a reloaded tab and a freshly opened one behave. Check a first visit with an empty profile too, since developers tend to have a worker installed and miss problems that only newcomers see.

Try more than one browser engine and at least one real phone. Feature support differs, particularly for background capabilities and notifications, so treat anything beyond fetch handling and caching as optional. The site should still work normally where a feature is missing, or where the worker fails to install at all.

Is it worth it?

For a web app people return to daily, or content they read on trains and in poor coverage, yes. For a small brochure site, an offline page adds little, and ordinary HTTP caching delivers most of the repeat-visit speed with far less risk.

Common questions

Can a service worker speed up the first visit?

Not much, since it isn't installed yet. Its benefits begin afterwards. First-visit speed depends on server response, file sizes and render-blocking resources.

Does it replace a CDN?

No. A worker helps one browser that has already visited. A CDN shortens the network path for everyone, including newcomers.

Written for 4Internet with AI writing tools and not reviewed line by line by a person. Check anything you rely on with the maker, provider or standard concerned. Report an error.

Keep reading

All 45 articles in HTTP, TLS & Web Performance →

Latest news on this topic