designwithfocus

JavaScript & front end

Web Worker vs Service Worker: Threads, Caches and Offline

By Design With Focus Team 6 min read
Two thread cards, one passing a message and one sitting on a cache

Short answer

Use a web worker for heavy script work beside the page, and a service worker when you need to intercept requests or serve a cache. Both run off the main thread and neither can touch the DOM. Web workers exchange data with postMessage. A service worker is downloaded, installed, and activated, and it requires a secure context.

Last verified against the sources listed below.

Key takeaways

  • MDN describes a web worker as a background thread so long work does not block the UI thread.
  • A service worker is an event-driven proxy for one origin and path, with no DOM access.
  • Web workers send data with postMessage. MDN says the data is copied, not shared.
  • Service workers run only in secure contexts. HTTPS is required, with a localhost exception.
  • The service worker lifecycle on MDN is download, then install, then activate.

Web worker vs service worker is a split between a helper thread and a network proxy. Pick a web worker when a calculation would stall the page. Pick a service worker when the job is to answer requests, including while the network is down.

MDN calls service workers a type of web worker, then gives them a separate API. The shared limits and the different jobs are both real. The language around either worker is still JavaScript.

How do the two workers differ?

A web worker computes beside the page. A service worker sits between the page and the network.

Topic Web worker Service worker
Thread Background thread, off the main UI thread Worker thread, separate from the page’s main script
DOM access No direct DOM access No DOM access
Lifetime A dedicated worker serves the script that created it Download, install, activate, then the browser can stop an idle worker
Typical job Long calculation without blocking the UI Intercept requests, cache files, offline responses
Secure context Not required by the pages opened here HTTPS, with a localhost exception

The lifetime row is the practical split. You start a dedicated worker from the page. The browser downloads and activates a service worker, and it can shut that worker down between events.

What does a web worker do?

A web worker runs a named script on a background thread so the main thread can keep painting.

MDN says you create the worker with a constructor such as Worker(). Inside it you get ordinary JavaScript, including fetch and XMLHttpRequest, with the note that responseXML is always null. You cannot touch the DOM from that thread.

Window is not available, though many methods exist on a shared mixin and show up through WorkerGlobalScope.

Dedicated workers serve one script. Shared workers can serve several windows, iframes, or other workers in the same domain, and scripts talk to them through a port. A worker may start another worker if that script stays on the same origin as the parent page.

Messages go through postMessage(), and the other side reads message events. MDN says the data is copied rather than shared. The HTML workers section calls workers relatively heavy-weight and says it would be inappropriate to launch one worker for each pixel of a four megapixel image.

Use one worker for a batch of work, not a swarm.

What does a service worker do?

A service worker is an event-driven script, registered for an origin and a path, that can intercept requests and fill a cache.

MDN says the lifecycle is download, install, then activate. The file downloads when a user first opens a controlled page. It is updated on a later navigation, or when an event fires and the worker has not been downloaded in the last 24 hours.

A byte-different file installs in the background and waits until no page still uses the old worker, unless you call skipWaiting().

The install event is the usual place to open a cache and put files in it. The activate event is the usual place to delete old caches. A fetch event can call respondWith() and return any response you build.

Because those setup events can take time, waitUntil() holds functional events until a promise settles.

web.dev’s service worker guide says the script acts as a network proxy even when the user is offline. It can answer from the Cache Storage API, from the network, or with a response you create. The same guide says the worker will not control the page on first load, and that you should treat it as optional for core features.

Installation does not ask the user for permission.

Scope follows the script URL. A worker at example.com/my-pwa/sw.js can control navigations at or under /my-pwa/. Only one service worker is allowed per scope.

In-memory data may not survive between runs, so web.dev points persistent data at IndexedDB or other storage. The browser can terminate a worker that has been idle for a few seconds, or busy for too long, and those timings differ by browser.

Why does HTTPS matter here?

Service workers run only in secure contexts, because a hostile network could otherwise inject a script with this much reach.

MDN states the rule as HTTPS, and it notes that browsers treat http://localhost as a secure context so local development still works. The W3C Service Workers specification says clients must also be secure contexts to register, to read registrations, and to message the worker. Its note allows localhost, 127.0.0.0/8, and ::1/128 for development.

Firefox can enable service workers over HTTP from a DevTools option. That switch is for testing, not for a public site.

A dedicated worker does not get that same sentence on the pages opened here. Do not copy the HTTPS rule across just because both are called workers.

Which worker should you choose?

Choose a web worker for CPU work the page is waiting on. Choose a service worker for request handling and offline shells.

A resize, a parse of a large file, or a search across a big list fits a dedicated worker. The page stays responsive, then applies the posted result. A shared worker fits when several tabs of the same origin need one background task.

Neither choice caches the next navigation by itself.

Choose a service worker when you want a cache, a custom response for a failed network, or a place to receive push and background sync. MDN lists those as intended uses. It also warns that the worker can delay the first load after a quiet period, because the browser must start the worker before it knows whether to use the cache or the network.

InstallEvent.addRoutes() can skip the worker for routes you already understand.

If the page feels slow only while a script runs, start with the worker thread. If the page fails with the network unplugged, start with the service worker. Page speed still depends on what that proxy decides to wait for.

Frequently asked questions

Can a service worker read the DOM?

No. MDN says service workers run in a worker context, so they have no DOM access, and they run on a different thread from the main JavaScript. Synchronous XHR and Web Storage are also unavailable there. A web worker has the same DOM limit. MDN says you cannot directly manipulate the DOM from inside a worker, and some Window methods are missing. If the result must change the page, post a message back and let the page script update the document.

Does a web worker require HTTPS?

The Web Workers page and the HTML workers section opened for this guide do not say a dedicated worker requires HTTPS. Service workers do. MDN says they are available only in secure contexts, so the document is served over HTTPS, and browsers treat as a secure context for local development. The W3C Service Workers spec adds 127.0.0.0/8 and ::1/128 for development. Do not assume a production HTTP host can register a service worker.

When does a waiting service worker take over?

MDN says a new file is installed in the background and stays the worker in waiting while any page still uses the old worker. It activates when those pages are gone. skipWaiting can activate it sooner, and Clients.claim can let the active worker take existing pages. web.dev adds that a reload does not hand control to the waiting worker by itself. The user has to leave the pages that the old worker still controls.

Can one page use both kinds of worker?

Yes. They answer different jobs. A dedicated worker, created with the Worker constructor, runs a named script for that page and returns results through messages. A service worker, registered with ServiceWorkerContainer.register, handles fetch events for its scope and can answer from the Cache Storage API. MDN also lists service workers as one type of web worker, beside dedicated and shared workers. The type does not merge the two APIs into one object.

What does postMessage send?

Worker.postMessage sends one message to a dedicated worker. MDN says the payload can be any value the structured clone algorithm can handle, and the Web Workers overview says the data is copied rather than shared. You can also transfer objects such as an ArrayBuffer, and the sender then sees a byteLength of 0. The same MDN page says Worker.postMessage is available in web workers except service workers. Service worker messaging uses a different interface.

Sources