A Worker runs a JavaScript file on a background thread so heavy work does not freeze the page. You create one with new Worker("worker.js").
The page and the worker talk with postMessage and onmessage (or message listeners). Workers cannot touch the DOM. They are ideal for CPU-heavy loops, parsing, and compression.
This page teaches what Worker is. Constructor, methods, and events live under this section.
No DOM access inside a worker.
Pass data in and out with messages. Update the page only from the main thread after you receive a result.
Syntax
JavaScript Syntax
Start a worker and exchange a message:
JavaScript
const worker = new Worker("worker.js");
worker.postMessage({ n: 40 });
worker.onmessage = function (event) {
console.log(event.data);
};
Reference
Core Ideas
Ideas every Worker tutorial builds on:
Idea
Example
Remember
Create
new Worker("app.js")
URL of the worker script
Send
worker.postMessage(data)
Structured-clone copy
Receive
worker.onmessage
Result arrives async
Inside worker
self.onmessage
Listen on self
No DOM
document …
Unavailable in workers
Terminate
worker.terminate()
Stop from the page
Code
JavaScript Examples
Three short programs that show how Worker works.
Example 1 — Construct a Worker
Pass the script URL to the constructor.
JavaScript
const worker = new Worker("worker.js");
console.log(typeof worker.postMessage);
Output
function
How It Works
new Worker("worker.js") starts the file.
postMessage is ready on the instance.
The browser loads the script asynchronously.
Example 2 — Round-trip a value
Page sends a number; worker replies with a result.