Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Worker — computation off the main thread

Worker runs a dedicated script independently of the page interface. It returns results asynchronously through messages, without direct access to the page DOM.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

const worker = new Worker(scriptURL, { type: "classic" });
worker.postMessage(value);
worker.onmessage = (event) => { /* event.data */ };
worker.terminate();

Worker is a browser Web API, not part of ECMAScript. It creates a dedicated worker with a separate global environment, without window or the page DOM. This lets expensive computation avoid blocking the interface.

new Worker(scriptURL) loads a classic script by default; { type: "module" } selects a module. postMessage() sends a message, and onmessage receives it through event.data. terminate() aborts execution; it is not graceful shutdown.

Messages use structured cloning, not shared references to ordinary objects. Functions cannot be cloned. A transfer list can move an ArrayBuffer, detaching the sender's buffer.

The example uses Blob to create an object URL for the script. If the constructor returns successfully, cleanup runs when the reply handler or the error handler is called. The page's Content Security Policy (CSP) must allow blob: workers. Even if CSP allows them, new Worker(url) can throw synchronously if the page enforces Trusted Types for script sinks and has no default Trusted Types policy. At that point, the object URL already exists, but neither handler has been installed, so the example does not revoke the URL. Check support in the target browser; Node 24 in the repository does not establish it.

Examples

const source = `
self.onmessage = ({ data }) => {
  self.postMessage(data.reduce((sum, n) => sum + n, 0));
};
`;
const url = URL.createObjectURL(
  new Blob([source], { type: "text/javascript" })
);
const worker = new Worker(url);
function cleanup() {
  worker.terminate();
  URL.revokeObjectURL(url);
}
worker.onmessage = ({ data }) => {
  console.log(data);
  cleanup();
};
worker.onerror = () => {
  console.error("Worker failed");
  cleanup();
};
worker.postMessage([2, 3, 5]);

Result

10

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources