Web Workers, Worklets, Server-Sent Events and Message Channels
When to use HTML workers, worklets, EventSource, and MessageChannel—how they communicate, their limits, and how to verify behavior.
This page summarises the WHATWG HTML Living Standard material on Web Workers, worklets, server-sent events (EventSource), and channel messaging (MessageChannel, postMessage). Supplemental notes from Chrome’s CSS Houdini documentation and Cloudflare Workers EventSource appear where they clarify runtime differences. Together, these APIs move work off the main UI thread or stream data from the server without polling—but they are not interchangeable.
Choosing an API: workers, worklets, EventSource, or message ports
Section titled “Choosing an API: workers, worklets, EventSource, or message ports”Pick the mechanism that matches who starts the work, how long it runs, and who talks to whom. Web Workers run author-controlled background scripts with an event-based postMessage API. Worklets are specification infrastructure: other specs (for example CSS Paint or Web Audio) register classes whose methods the user agent calls; authors do not use the base worklet API directly. EventSource opens a long-lived HTTP stream for server→client push in the text/event-stream format. window.postMessage and MessageChannel connect windows, iframes, or workers with structured messages and transferable ports.
| Mechanism | Who drives execution | Typical duration | Main API shape |
|---|---|---|---|
| Dedicated / shared worker | Page or worker script | Long-lived, few instances | Worker, onmessage, postMessage |
| Worklet | User agent invokes registered methods | Short, pipeline-bound | worklet.addModule(), register handlers in other specs |
EventSource |
Server pushes over HTTP | Long connection, auto-reconnect | new EventSource(url), message events |
MessageChannel |
Either port endpoint | While ports are entangled | MessageChannel, port.postMessage |
Web Workers: background scripts and UI responsiveness
Section titled “Web Workers: background scripts and UI responsiveness”What Web Workers are for (Worker off the main thread)
Section titled “What Web Workers are for (Worker off the main thread)”Web Workers run scripts in the background, independently of user-interface scripts on the main document.
This specification defines an API for running scripts in the background independently of any user interface scripts.
This allows for long-running scripts that are not interrupted by scripts that respond to clicks or other user interactions, and allows long tasks to be executed without yielding to keep the page responsive.
— WHATWG, 10 Web workers — 10.1.1 Scope
Workers are long-lived, with high start-up cost and high per-instance memory cost; the spec expects a small number of workers per page, not hundreds.
Dedicated workers vs shared workers vs service workers
Section titled “Dedicated workers vs shared workers vs service workers”The standard defines two worker kinds in the workers chapter; service workers are a third kind defined elsewhere.
This standard defines two kinds of workers: dedicated workers, and shared workers. Dedicated workers, once created, are linked to their creator, but message ports can be used to communicate from a dedicated worker to multiple other browsing contexts or workers. Shared workers, on the other hand, are named, and once created any script running in the same origin can obtain a reference to that worker and communicate with it. Service Workers defines a third kind.
— WHATWG, 10.2 Infrastructure
Dedicated workers suit one owner (one tab’s computation). Shared workers suit one origin sharing background state across tabs. Service workers are out of scope here except as a distinct global type.
Creating a dedicated worker: classic script or module
Section titled “Creating a dedicated worker: classic script or module”Creation needs a script URL. Classic workers use the one-argument form; module workers need { type: "module" }.
var worker = new Worker('helper.js');var moduleWorker = new Worker('helper.mjs', { type: "module" });Module workers gain import, strict mode by default, and isolated top-level scope. In a module worker, importScripts() throws—use import instead (module worker example).
postMessage, structured cloning, and ArrayBuffer transfer
Section titled “postMessage, structured cloning, and ArrayBuffer transfer”Dedicated workers use MessagePort semantics behind the scenes. The main thread listens with worker.onmessage; the worker uses onmessage and postMessage on event.data. For large binary data, pass transferables in the second argument so buffers move instead of copying:
worker.postMessage({ operation: 'find-edges', input: buffer, threshold: 0.6,}, [buffer]);The implicit port does not expose MessagePort.start(); message flow begins when the worker is created (communicating with a dedicated worker).
Nested workers and libraries often combine MessageChannel with postMessage(..., [port2]) so a worker exposes multiple logical conversations without changing the public API—patterns in the crypto library worker example.
Worker lifetime, event loop, and errors
Section titled “Worker lifetime, event loop, and errors”A worker event loop handles events, callbacks, and networking—not full window rendering. When the worker global’s closing flag is true, new tasks are discarded: timers stop, pending notifications drop, and so on (10.2.2 The event loop).
Lifetime is expressed through actively needed, protected, permissible, and suspendable states; shared workers additionally use between-loads and extended lifetime timeouts (often on the order of seconds). Uncaught errors in worker scripts are reported against the worker’s WorkerGlobalScope (runtime script errors).
Serial script execution and SharedArrayBuffer
Section titled “Serial script execution and SharedArrayBuffer”For most APIs, scripts cannot observe other scripts running at the same time—even with workers, implementations behave as if all script execution were serialized across globals.
To avoid exposing web authors to the complexities of multithreading, the HTML and DOM APIs are designed such that no script can ever detect the simultaneous execution of other scripts.
SharedArrayBuffer is the notable exception; only dedicated and shared worker agents (not worklet agents) may use atomics APIs that can block (integration with the JavaScript agent formalism).
Common Web Worker mistakes
Section titled “Common Web Worker mistakes”- Spawning too many short-lived workers instead of pooling or delegating ranges to a fixed pool (multicore delegation example).
- Calling
importScripts()inside a module worker. - Assuming the main thread can touch worker globals directly—only messages and transferred ports cross the boundary.
- Ignoring that the creator
Workerobject may be garbage-collected while computation still runs; lifetime rules are subtle (worker’s lifetime).
Worklets: pipeline hooks, not general background threads
Section titled “Worklets: pipeline hooks, not general background threads”Worklet infrastructure (authors use typed worklets, not Worklet alone)
Section titled “Worklet infrastructure (authors use typed worklets, not Worklet alone)”Worklets run scripts outside the main JavaScript environment of the window, without mandating threads.
Worklets are a piece of specification infrastructure which can be used for running scripts independent of the main JavaScript execution environment, while not requiring any particular implementation model.
The worklet infrastructure specified here cannot be used directly by web developers. Instead, other specifications build upon it to create directly-usable worklet types, specialized for running in particular parts of the browser implementation pipeline.
— WHATWG, 11 Worklets — Introduction
Chrome’s Houdini documentation states that Houdini needs code that may run every frame, which would be impractical with web workers’ weight—hence worklets.
How worklets differ from Web Workers
Section titled “How worklets differ from Web Workers”Worklets overlap conceptually with workers but differ in threading model, API, and lifetime.
Worklets are similar to web workers. However, they:
Are thread-agnostic. That is, they are not designed to run on a dedicated separate thread, like each worker is. Implementations can run worklets wherever they choose (including on the main thread).
Are able to have multiple duplicate instances of the global scope created, for the purpose of parallelism.
Do not use an event-based API. Instead, classes are registered on the global scope, whose methods are invoked by the user agent.
Have a reduced API surface on the global scope.
— WHATWG, 11.1.1 Motivations
Worklet agents have [[CanBlock]] false, so unlike dedicated worker agents they are not required to map one-to-one to OS threads; a worklet may even run on the main thread (agents and event loops).
Loading worklet modules and writing safe handler code
Section titled “Loading worklet modules and writing safe handler code”Scripts load with worklet.addModule(url); completion order depends on network timing. Specs that allow parallelism require at least two WorkletGlobalScope instances per worklet and may invoke author methods in implementation-defined order—handlers should be idempotent (same input → same output) and often stateless when speculative evaluation is allowed (code idempotence, speculative evaluation).
WorkletGlobalScope lifetime ties to the document; user agents may terminate scopes when idle, on policy grounds, or when loops exceed limits (the worklet’s lifetime).
Server-sent events: EventSource and text/event-stream
Section titled “Server-sent events: EventSource and text/event-stream”What EventSource does (server push over HTTP)
Section titled “What EventSource does (server push over HTTP)”EventSource lets servers push data to pages over HTTP (or coordinated push proxies on mobile networks).
To enable servers to push data to web pages over HTTP or using dedicated server-push protocols, this specification introduces the EventSource interface.
Using this API consists of creating an EventSource object and registering an event listener.
— WHATWG, 9.2.1 Introduction
Default events use type message; named types use addEventListener. Streams are always UTF-8; redirects follow HTTP 301/307; 204 No Content tells the client not to reconnect.
Wire format and MIME type
Section titled “Wire format and MIME type”The media type is text/event-stream (IANA registration). Fields are line-based (data:, event:, id:, comment lines starting with :). Multiple data: lines join with newlines in the dispatched MessageEvent. A blank line ends an event (event stream format).
Cloudflare’s HTTP SSE guide summarises the same framing: data: … terminated by a blank line, optional event: and id: lines.
Reconnection, Last-Event-ID, and operational pitfalls
Section titled “Reconnection, Last-Event-ID, and operational pitfalls”When the connection drops, the user agent reestablishes the connection (with optional backoff). On retry, if a last event ID was stored, the client sends a Last-Event-ID header (processing model, Last-Event-ID).
Authoring notes from the spec: send comment heartbeats (: …) every ~15s through old proxies; avoid relying on client IP for session identity; HTTP chunking at the wrong layer can delay events; multiple tabs to the same origin may hit per-server connection limits—mitigations include shared workers holding one EventSource (authoring notes).
On the server, CORS applies to cross-origin streams; streams can exhaust client resources if unbounded (text/event-stream security considerations).
EventSource in Cloudflare Workers
Section titled “EventSource in Cloudflare Workers”In Cloudflare Workers, EventSource matches the web API but may pass a custom fetcher binding instead of global fetch (EventSource constructor). That option is specific to the Workers runtime.
Message channels: postMessage, MessageChannel, and workers
Section titled “Message channels: postMessage, MessageChannel, and workers”Cross-document postMessage (windows and iframes)
Section titled “Cross-document postMessage (windows and iframes)”window.postMessage(data, targetOrigin) delivers a message event to another browsing context. Receivers must check event.origin before trusting event.data (cross-document messaging introduction).
MessageChannel and MessagePort.start()
Section titled “MessageChannel and MessagePort.start()”Channel messaging is a two-way pipe: each port delivers what the other sends, as DOM events without blocking tasks.
Communication channels in this mechanism are implemented as two-ways pipes, with a port at each end. Messages sent in one port are delivered at the other port, and vice-versa. Messages are delivered as DOM events, without interrupting or blocking running tasks.
— WHATWG, 9.4.1 Introduction
With onmessage, start() is implied. With addEventListener('message', …), you must call port.start() so queued messages are not dropped (examples).
Ports can be transferred into workers via postMessage(..., [channel.port2]), which underpins worker-hosted libraries and capability-style APIs (ports as object-capability model). Closing ports when done reduces memory pressure; undrained ports can delay garbage collection (ports and garbage collection).
How to check this on your site
Section titled “How to check this on your site”-
Open the page that uses a worker, worklet, or
EventSource, and use the browser development console to confirm workers load without network errors and thatEventSourcediagnostics (URL, CORS, parsed events) match expectations—the HTML spec urges detailed console reporting forEventSource, especially onerrorevents (implementation advice). -
For a dedicated worker, verify round-trip messaging: the main script receives
onmessagepayloads and, if used, transferredArrayBufferobjects are detached on the sending side afterpostMessagewith transfer list (communicating with a dedicated worker). -
For SSE, fetch the stream URL and confirm the response
Content-Typeistext/event-stream, body lines follow thedata:/ blank-line rules, and multi-linedata:fields produce the expected singleevent.datastring (event stream format). -
For
MessageChannel, if handlers useaddEventListener, callport.start()and confirm messages arrive; after tests, callport.close()on both ends where the spec recommends explicit cleanup (web messaging examples). -
You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact wording you are asking about.