A service worker is a script that a web browser runs separately from a web page to handle events associated with a website or web application. Its best-known capability is intercepting requests and supplying responses from the network, local storage, or application-defined logic. This makes it possible for a site to load previously stored content without a network connection, coordinate updates to application resources, and respond to certain events when no application page is open.
Service workers are normally written in JavaScript and operate within a browser-managed security and execution environment. They cannot directly manipulate a page’s document, and their execution can stop between events. What persists is a registration, together with separately stored application data—not a continuously running program. Their design therefore combines event-driven execution, explicit storage, and a lifecycle that separates installing a new version from making it responsible for existing pages.
Service workers are a foundational technology for progressive web applications, but they are not limited to installed applications and do not by themselves make a website installable or fully functional offline. Their practical behavior depends on request routing, cache policy, storage availability, browser support, and coordination between application versions.
Origins and standardization
Service workers emerged from efforts to give web applications more dependable behavior under slow, unreliable, or absent network connectivity. Earlier web platforms generally assumed that navigation would retrieve a document from a server. Although ordinary browser caching could reuse resources, applications had limited control over which resources formed a coherent offline experience or what response should appear when a request failed.
An important predecessor was Application Cache, commonly called AppCache. It used a manifest to identify resources for offline use and provided some fallback and network-selection rules. Its declarative model was relatively simple for small applications, but its update behavior and interactions with navigation proved difficult to manage in more complex sites. AppCache did not provide a general programmable request handler. Service workers instead placed explicit application logic between eligible requests and response sources, allowing different policies for documents, images, application data, and other resources.
Early service-worker designs took shape in 2013 and 2014. Alex Russell and Jake Archibald were prominent contributors to the design and its explanation to developers. Browser deployment followed over several years: Chrome 40 introduced service-worker support in January 2015, Firefox 44 followed in January 2016, and Safari 11.1 added support in 2018. Microsoft Edge also gained support in 2018. These milestones concerned the core facility; related capabilities such as push delivery, background synchronization, and installation integration followed different implementation schedules.
The specification is developed through the World Wide Web Consortium and depends on several other web-platform standards. Its request interception relies on the Fetch processing model; its execution model builds on workers and the HTML event loop; and persistent resource storage is supplied through the Cache API. Notifications, push messaging, and background synchronization have their own specifications rather than being interchangeable names for service workers.
This division matters for interpreting support claims. A browser may implement registration, activation, and fetch interception while omitting a particular background API. Likewise, an application can use a service worker solely to improve network resilience without offering push notifications. The core technology is an execution and interception framework, not a single bundled application feature.
Execution model and separation from web pages
A service worker runs in a ServiceWorkerGlobalScope, rather than a page’s Window environment. It has no direct access to the Document Object Model, so it cannot read an element, change a stylesheet, or update an interface by calling ordinary document methods. Communication with pages instead uses mechanisms such as postMessage(), message channels, and the Clients interface. A page receives a message and performs any corresponding interface changes in its own execution environment.
This resembles other web workers in separating background script execution from page scripting, but the ownership model differs. A dedicated worker is normally created by a particular page for that page’s work. A service worker belongs to a registration associated with a storage context and URL scope. It can serve multiple eligible clients and can be started to handle a supported event even when no application window is open. The word “worker” does not imply that an application controls a permanent operating-system thread.
Execution is based on events and asynchronous programming. A browser starts the worker when necessary, evaluates its script, and dispatches events such as install, activate, fetch, or push. JavaScript handlers run through an event loop, while network and storage operations usually return promises. Fetching a response or reading a cache therefore need not block other browser activity, although CPU-intensive JavaScript can still delay work within the worker itself.
The browser may terminate an idle worker and later create a fresh execution environment for another event. Consequently, global variables are unsuitable as authoritative persistent state. A variable recording an outgoing message queue, for example, can disappear before the next event. Durable records belong in an appropriate storage system, such as IndexedDB, and handlers must be able to reconstruct their state when execution resumes. Top-level event listeners are normally registered during initial script evaluation so that the browser can dispatch events predictably.
Two methods connect asynchronous work to event handling. event.waitUntil(promise) tells the browser that an extendable event has associated work whose completion matters. During installation, rejection can cause the new worker to fail installation. For fetch events, event.respondWith() supplies the promise for the response. Neither method grants unlimited runtime: browsers can impose execution limits, abort work, or terminate execution under exceptional conditions. The model is therefore closer to a restartable event handler than to an always-running server or daemon.
Registration, origins, and scope
A page generally registers a service worker through navigator.serviceWorker.register(). Registration identifies a script URL and, optionally, a scope. A simple registration might associate /sw.js with /, making the registration eligible to control documents throughout that origin. Calling registration repeatedly for the same scope normally refers to the existing registration and may initiate an update check; it does not create an independent permanent worker on every page visit.
Service workers require a secure context. In ordinary deployment this means HTTPS, protected using Transport Layer Security. Development environments such as localhost receive special treatment as potentially trustworthy origins. This requirement reflects the power of request interception: a script substituted during an insecure transfer could otherwise install persistent behavior that continued affecting later visits.
The worker script must be fetched from the registering page’s origin. The browser checks the script response, including whether it has an acceptable JavaScript media type. Scope is also constrained. By default, a script at /app/sw.js can register for the directory /app/ and its descendants, but not for the entire origin. A server can explicitly permit a broader scope with the Service-Worker-Allowed response header. This prevents a script placed in a narrow directory from automatically claiming unrelated paths.
Scope concerns which clients a registration may control, not simply which request URLs its handler may see. A controlled page can request resources from other paths or other origins, and those requests can generate fetch events in its controller, subject to the Fetch model and security rules. Conversely, a page outside the worker’s scope does not become controlled merely because it downloads an image whose URL lies within that scope. Where registrations overlap, the most specific matching scope is relevant to client selection.
Registering a worker also does not normally make the current page immediately controlled. On a first visit, the page may finish loading while the worker installs and activates in the background; a later navigation can then obtain a controller. clients.claim() allows an active worker to take control of eligible existing clients, while navigator.serviceWorker.controller exposes a page’s current controller. The ready promise indicates that the page has an applicable registration with an active worker, but it is not equivalent to a guarantee that the current document already has a controller.
Installation, activation, and version replacement
A service-worker registration can have an installing worker, a waiting worker, and an active worker. These are roles within the registration, not three permanently running processes. An individual worker moves through states including installing, installed, activating, activated, and redundant. A successful update commonly leaves a new version waiting while an older version remains active for existing clients.
The install event is the main opportunity to prepare resources required by a version. An application might open a version-specific cache and download its interface shell, scripts, and an offline error document. Passing that operation to event.waitUntil() makes successful completion part of installation. If required downloads fail and the associated promise rejects, installation fails. An existing active worker can remain in service rather than being replaced by a version whose essential resources are unavailable.
A newly installed worker usually waits until the previous active worker is no longer needed by clients using it. This prevents a page loaded with one application version from unexpectedly receiving responses governed by another version’s assumptions. Multiple tabs can therefore keep an older worker active. Reloading one tab does not necessarily remove every old client, so a waiting update can remain visible in developer tools even after a reload.
The waiting worker can call skipWaiting() to request earlier activation. An activating worker can then use clients.claim() to take control of eligible clients. These are distinct operations: skipping the waiting phase changes when the worker becomes active, while claiming changes the controllers of existing eligible clients. Using both can make an update take effect quickly, but it can also combine an old page’s JavaScript with new request-routing logic. Applications that require tightly matched versions often coordinate an explicit reload instead.
The activate event provides a point for migration and housekeeping, such as removing obsolete application caches. Work passed to its waitUntil() can delay functional event processing until activation work finishes. Cleanup must account for clients and other registrations sharing storage; cache names are not automatically isolated by registration scope.
Browsers check for updated worker scripts during defined registration and navigation activities, and applications can request a check with registration.update(). Updates are based on script bytes rather than a developer-assigned version number. The updateViaCache option affects use of the browser’s HTTP cache during update checks. Keeping the registration URL stable allows the lifecycle machinery to replace the worker, while versioned cache names or resource hashes distinguish the assets it manages.
Fetch interception and request–response semantics
The defining service-worker capability is participation in the browser’s Fetch API processing. When an eligible request triggers a fetch event, the handler receives a Request and may provide a Response. This can happen for document navigation, images, stylesheets, scripts, and requests initiated by page JavaScript. Request interception does not require replacing every response: a handler can leave an event unanswered, allowing ordinary network processing to continue.
To take responsibility for a request, the handler calls event.respondWith() during event dispatch, commonly with a promise that later resolves to a response. The promise may fetch from a server, inspect a cache, construct a new response, or combine several operations. If the supplied promise rejects, or resolves to an unacceptable response, the request fails; it does not automatically fall back to the network. Fallback behavior must be part of the handler’s logic.
Request and response bodies generally use streams that can be consumed only once. If a network response is both returned to a page and written to a cache, a handler commonly clones it before one consumer reads the body. Similarly, reading a request body for logging or queuing requires care if the request will also be forwarded. Cloning creates another readable branch, not an unlimited free copy: buffering and backpressure can affect memory use when branches are consumed at different rates.
Security constraints continue to apply. Cross-origin resource sharing determines when cross-origin response contents are available to scripts. A cross-origin request made in no-cors mode can produce an opaque response whose body and headers cannot be inspected by the worker. Such responses can be useful for resources such as images, and can be stored with suitable Cache API operations, but their opacity complicates validation and error detection.
Network failure and unsuccessful HTTP status codes are different cases. A server response with status 404 or 500 normally fulfills a fetch promise with a response; a connection failure typically rejects it. An offline fallback that handles only rejected promises therefore does not automatically replace server error responses. A handler must inspect status or response.ok when its policy depends on HTTP success.
Navigation also has a performance-specific feature called navigation preload. Once enabled, the browser can begin the navigation request while starting the service worker. The handler can use event.preloadResponse rather than initiating a duplicate fetch. This reduces startup delay in network-oriented navigation strategies, but requires deliberate coordination with caching and response selection.
Cache Storage and offline response strategies
The Cache API supplies explicit storage for request–response pairs. CacheStorage, available through caches, manages named caches; each Cache provides operations such as match(), put(), and delete(). This storage is separate from the browser’s ordinary HTTP cache. In particular, explicit Cache API entries do not automatically expire according to HTTP freshness directives. Application code determines when to reuse, replace, or remove them.
Cache matching is more structured than a simple string-to-file lookup. Request URL, method, and response Vary headers can affect matching, and query strings normally distinguish entries. Ignoring query strings can improve reuse for some tracking parameters but can also confuse genuinely different resources. Cache API storage operations are oriented around GET requests; saving arbitrary POST operations for later replay generally requires storing their data elsewhere rather than treating them as ordinary cached responses.
Several recurring strategies express different trade-offs:
- Cache first returns a matching stored response and uses the network when no match exists. It suits resources whose content is immutable under a versioned URL.
- Network first attempts the network and falls back to storage after failure or a chosen timeout. It favors fresh content while retaining an offline path.
- Stale while revalidate returns a stored response promptly while fetching a replacement for future requests. Its background update must remain associated with the event through
waitUntil(). - Network only and cache only deliberately use a single source, which can be appropriate for sensitive requests or prepackaged resources.
Pre-caching and runtime caching address different resource sets. Pre-caching stores selected assets during installation, often using a build-generated manifest with content revisions. Runtime caching adds resources when requests occur. An offline application might pre-cache its navigation shell while caching recently viewed articles at runtime. Merely storing scripts and styles does not preserve server-side search results, authentication state, or data that the user has never downloaded.
Storage is finite and browser-managed. Quotas depend on the browser and environment, writes can fail, and data can be evicted under storage pressure. Persistent-storage permission can change eviction treatment where supported, but does not protect data against user deletion or every browser policy. Responses, IndexedDB records, and application preferences therefore need handling for missing or partially available local state.
Cache design also has privacy consequences. A cache name is not a user authorization boundary. Personalized responses can outlive logout or account changes unless the application explicitly coordinates their removal and use. Cache rules must distinguish public immutable assets from account-specific data, and a response header such as Cache-Control: no-store does not by itself prevent application code from explicitly placing a response in Cache Storage.
Push messaging and deferred background work
Service workers provide an event target for several capabilities that can operate without an open application page. The best-known is web push, which combines a browser-managed subscription, a push service, an application server, and the Push API. A subscription gives the application server information needed to address and encrypt messages for that browser subscription. The browser can start the service worker when a push message arrives and dispatch a push event.
Push delivery and notification display are distinct operations. A push message can carry data for the worker, while registration.showNotification() asks the browser or operating system to display a user-facing notification. Notification interaction can later trigger notificationclick, allowing the worker to focus an existing application window or open an appropriate URL. These operations remain subject to permissions, browser policies, and platform-specific restrictions.
Push is not a reliable general-purpose channel for silent continuous computation. Browsers can require user-visible effects, restrict abusive usage, and delay delivery according to connectivity or operating-system behavior. Subscriptions can expire or become invalid, and the application server must handle delivery failures. A push message is therefore often used as a signal to retrieve current state rather than as the sole authoritative record of a transaction.
The Background Synchronization API addresses another problem: retrying deferred work when connectivity becomes suitable. A page can register a synchronization tag after storing an intended operation locally. The browser later dispatches a sync event, and the worker attempts the work. If the event’s associated promise rejects, the browser may retry according to its implementation. Support and scheduling vary, so registration is not a promise of execution at a specified time.
Durable background operations require an explicit queue, commonly in IndexedDB. Consider submitting a form while offline. The application stores the payload and an operation identifier, then tries delivery during an appropriate event. If the server accepts the operation but the worker stops before recording success, a later attempt can send it again. Server-side deduplication or an idempotent operation design prevents duplicate effects. Background synchronization does not create exactly-once delivery or a database transaction spanning local storage and a remote server.
Periodic background synchronization is a separate, less widely available capability, governed by browser decisions rather than precise timers. Ordinary setTimeout() and setInterval() calls are not substitutes for it because the worker can stop when idle. Background facilities are best understood as constrained scheduling opportunities, with application correctness remaining dependent on durable state and recovery logic.
Security, privacy, and trust boundaries
A service worker is powerful because it can influence what controlled pages receive, including navigation documents and executable resources. If an attacker gains the ability to register a malicious worker under a useful scope, the resulting behavior may persist across later visits until the registration is replaced or removed. This makes service-worker deployment part of a site’s cybersecurity boundary rather than merely a performance configuration.
HTTPS protects the transport used to retrieve the worker and controlled resources, but it does not establish that application code is trustworthy. A compromised deployment pipeline, malicious same-origin script endpoint, or sufficiently capable cross-site scripting attack can still undermine the registration process. Registration’s same-origin and scope restrictions limit authority; they do not compensate for an origin that already serves attacker-controlled executable code.
Content Security Policy can constrain worker creation and resource loading. The policy governing a page can restrict which worker sources it may register, while policy delivered with a worker script governs relevant behavior in that worker’s environment. These controls complement server-side restrictions on script hosting and appropriate scope boundaries. They are not a substitute for treating worker code as trusted application code with substantial persistence and interception privileges.
A worker remains inside the browser’s security model. It cannot simply read arbitrary local files, control other origins, or bypass cross-origin response restrictions. HttpOnly cookies are not exposed as readable cookie values to worker JavaScript, although eligible requests can still carry credentials according to their credential mode and cookie rules. The distinction between reading a credential and causing an authenticated request is important: lack of direct cookie access does not make request interception harmless.
Privacy protections also affect the persistence model. Browsers may partition storage according to embedding context, restrict third-party registrations, or apply special rules in private browsing. Registration scope is not a universal cross-site identity. Applications cannot assume that a registration and its caches will be shared across every context in which their origin appears.
Finally, unregistering a worker and deleting application storage are separate operations. unregister() removes the registration, but does not automatically clear named caches or IndexedDB databases, and existing controlled clients may remain affected until their relationship with the worker ends. Security recovery and user-data removal therefore require attention to registrations, open pages, stored responses, and durable application records as distinct pieces of state.
Application architecture, testing, and operational limits
Service workers introduce a second application lifecycle alongside page navigation and server deployment. A page, its controlling worker, cached assets, local databases, and the server may each represent a different version of the application. This makes compatibility a central software engineering problem. A deployment that deletes every old script immediately can break a still-open page that later requests one of those scripts, even if the new worker and new page work correctly together.
Versioned assets and explicit cache namespaces help manage this problem. Content-hashed filenames let immutable resources coexist, while a stable worker URL lets the browser discover changes. A worker can preserve resources needed by older clients or coordinate migration before removal. Local database schema changes need similar care: a newly activated worker and an older page can otherwise disagree about record shape, queue format, or transaction behavior.
Request handling also resembles a small distributed system. Network availability is uncertain, local writes and remote commits are separate operations, and multiple tabs can act on shared data concurrently. A race condition can arise when two clients both update a queue or infer state from an outdated cached response. IndexedDB transactions, operation identifiers, explicit message protocols, and server-side conflict handling address different parts of this problem; no single cache strategy solves all of them.
Development tools expose registrations, lifecycle states, controlled clients, caches, and worker execution logs. Useful tests distinguish a first visit from a returning visit, a fully terminated worker from one kept alive by debugging, and a single tab from several tabs using different versions. Other important cases include failed installation, quota exhaustion, account switching, rejected push permission, interrupted uploads, and server responses that return errors rather than connection failures.
Offline simulation alone is insufficient. A request can hang on a weak connection rather than fail promptly, a captive portal can return unexpected content, and a browser can evict storage between visits. Testing therefore includes slow networks, interrupted responses, unavailable cached assets, and restarts between individual queue-processing steps. Developer tools themselves can alter behavior by forcing updates, bypassing interception, or changing worker lifetime, so these settings must be distinguished from normal operation.
Service workers can improve repeat-load performance, but they can also add startup latency, duplicate network requests, or retain unnecessary data. Measurements distinguish cold and warm caches, controlled and uncontrolled visits, and worker startup from request processing. Libraries such as Workbox provide pre-caching and routing abstractions, but their generated rules still operate within the same lifecycle and storage constraints. Browsers without an applicable worker, users who have cleared storage, and first-time visitors continue to depend on the application’s ordinary network-delivered behavior.