Web Workers API
Explain which thread should update a paragraph after a worker returns a result.
Understand the topic
A dedicated web worker runs JavaScript in a separate execution context so CPU-heavy work can avoid blocking the page. Workers communicate through messages and cannot manipulate the DOM directly. The worker script must be served in an allowed context and origin. Terminate workers when finished and handle errors rather than leaving background work running indefinitely.
Worked example
// main.js
const worker = new Worker("worker.js");
worker.onmessage = (event) => {
document.querySelector("output").textContent = event.data;
worker.terminate();
};
worker.onerror = () => { worker.terminate(); console.log("Worker failed."); };
worker.postMessage(12);
// worker.js, a separate file
self.onmessage = (event) => self.postMessage(event.data * event.data);
Create two actual files and an output element on your page. The worker calculates 144 and the main thread updates the DOM. This is a multi-file example, not one script to paste unchanged.
Practice
Explain which thread should update a paragraph after a worker returns a result.
Show a suggested answer
The main page thread updates the DOM in its message handler. A worker has no document object for manipulating page elements.Common mistake
Do not combine the two file examples into the same script and expect a worker to be created automatically.