DEV Community

Cover image for Service Workers Deep Dive: What Actually Happens in the Browser
Mohammad
Mohammad

Posted on

Service Workers Deep Dive: What Actually Happens in the Browser

What Is a Service Worker?

A Service Worker is a JavaScript file that runs in the background, separate from the main page.

Key characteristics:

  • Runs on a different thread than the UI
  • Has no access to the DOM or window
  • Uses only asynchronous APIs
  • Can intercept and handle network requests

Service Workers act as a programmable network proxy between your application and the internet. Because they run outside the page lifecycle, the browser can start, stop, or restart them whenever needed. For this reason, they must not depend on in-memory state.


Registering a Service Worker

To use a Service Worker, you register it from your page:

navigator.serviceWorker.register("/sw.js");
Enter fullscreen mode Exit fullscreen mode

When this runs, the browser:

  1. Fetches the sw.js file
  2. Compares its content with the previously stored version
  3. Starts the lifecycle if the file is new or changed

The comparison is content-based. Even a one-character change in the file triggers a new install. File names, comments, or version variables do not matter unless they change the actual bytes of the file.


The Lifecycle: install → activate

Install

The install event is the first event fired for a new version of a Service Worker.

Its main purpose is to prepare the application for offline usage by caching required assets.

self.addEventListener("install", (event) => {
  event.waitUntil(
    caches.open("app-shell-v1").then((cache) => {
      return cache.addAll([
        "/",
        "/styles.css",
        "/app.js"
      ]);
    })
  );
});
Enter fullscreen mode Exit fullscreen mode

event.waitUntil() tells the browser not to finish installation until the promise resolves. If this promise rejects, the Service Worker is discarded and never reaches the activate phase. This makes install an atomic step: it either fully succeeds or fails completely.


Activate

After installation, the Service Worker moves to the activate phase.

This event is typically used to:

  • Remove old cache versions
  • Release unused resources

Only one Service Worker version can be active at a time. If an older version is controlling open pages, the new one waits. This prevents a page from changing its controlling logic while it is running.


Page Control and Reloading

A page decides whether it is controlled by a Service Worker at load time.

This means:

  • The page that calls register() is not controlled
  • A reload or new tab is required for control to take effect

One Service Worker can control many pages at once. All controlled pages share the same worker instance. Global variables are shared and unreliable because the worker can be terminated and restarted at any time. Persistent data must be stored in Cache API or IndexedDB.


Cache API (Detailed)

The Cache API is the primary persistent storage mechanism used by Service Workers to store network responses.

At its core, the Cache API stores Response objects, each associated with a Request object as its key. This means the cache behaves like a map:

Request  →  Response
Enter fullscreen mode Exit fullscreen mode

What exactly is stored?

  • Only Response objects
  • Metadata such as headers, status code, and body stream
  • No automatic serialization of custom data

The Cache API does not store raw files or URLs. It stores full HTTP responses, exactly as they were returned by the network.


How matching works

When you query the cache, the browser tries to find a matching entry based on:

  • Request URL
  • HTTP method (usually GET)
  • Vary-related headers

This matching logic closely follows standard HTTP caching rules, but it is fully controlled by your code. Nothing is automatically added or removed unless you explicitly do so.


Cache lifetime and persistence

Cache entries:

  • Do not expire automatically
  • Are not evicted based on time or size
  • Remain stored until explicitly deleted by your code or the user clears site data

Because of this, cache cleanup is a responsibility of the Service Worker, usually handled during the activate phase.


Scope and isolation

Cache API storage is scoped to the origin, defined as:

protocol + domain + port
Enter fullscreen mode Exit fullscreen mode

This means:

  • Each domain has its own isolated cache storage
  • Subdomains do not share caches
  • Other websites cannot read or modify your cache

This isolation is critical for security and data integrity.


Debugging and inspection

Cache contents can be inspected via browser DevTools:

Application → Cache Storage
Enter fullscreen mode Exit fullscreen mode

From there you can:

  • View cached requests and responses
  • Manually delete cache entries
  • Simulate cache-related edge cases during development

Recap

  • Service Workers run outside the page lifecycle and are event-driven
  • Registration is required and update detection is based on file content
  • The install phase prepares resources and must fully succeed
  • Only one Service Worker version can be active at a time
  • Page control is decided at load time, not dynamically
  • Cache API stores full HTTP responses keyed by requests
  • Cache data is persistent, origin-scoped, and fully controlled by code
  • Proper cache management is essential for predictable PWA behavior

Top comments (0)