What is the Web Workers API
· Category: HTML & CSS
Short answer
Web Workers let you execute JavaScript on a background thread, separate from the main UI thread. They are useful for heavy computation without blocking user interactions.
Steps
- Create a worker file with a
messageevent listener. - Instantiate
new Worker('file.js')from your main script. - Communicate using
postMessageandonmessage.
Example
// worker.js
self.onmessage = (e) => {
const result = e.data * 2;
self.postMessage(result);
};
// main.js
const worker = new Worker('worker.js');
worker.postMessage(10);
worker.onmessage = (e) => console.log(e.data);
Tips
- Workers cannot access the DOM directly.
- Use
terminate()to stop a worker when done. - SharedWorkers allow multiple tabs to share the same worker thread.