What is Web Worker
the power and limit of web worker in browser
Web worker is a background thread in browser, it can run in parallel with the main thread. It can be used to offload heavy tasks from the main thread, such as computation, data processing, etc.
Why Web Worker?
JavaScript that runs for a long time on a page's main thread can delay event handling and rendering. A Web Worker provides a separate execution context for work that can run independently, helping the page remain responsive while that work continues. Workers are useful for tasks such as image processing, parsing large files, or calculations; they do not make the task itself faster in every case.
The limitations of Web Worker
Workers run in a different global context from the page. A worker cannot directly access or modify the page's DOM, so the main thread must apply UI changes. A page and its worker communicate through messages, typically with postMessage() and message event handlers. Message data is structured-cloned by default; transferable objects can move ownership instead, which can avoid copying supported large buffers.
Workers do not have the page's window or document, so APIs tied to the current page and DOM, such as document.querySelector(), are unavailable there. Many other APIs are available in workers, including fetch() and IndexedDB.
Example
The page creates a worker and sends it two numbers. The worker multiplies them and sends the result back. The page updates the DOM after receiving the message.
main.js:
const worker = new Worker(new URL("./worker.js", import.meta.url), {
type: "module",
});
worker.onmessage = (event) => {
document.querySelector("#result").textContent = event.data;
};
worker.postMessage({ first: 6, second: 7 });
worker.js:
self.onmessage = (event) => {
const { first, second } = event.data;
self.postMessage(first * second);
};
postMessage() sends the request to the worker; the worker's message handler processes it and self.postMessage() returns the result. The page's message handler receives that result and performs the DOM update. For more details, see MDN's guide to using Web Workers.