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

  1. Create a worker file with a message event listener.
  2. Instantiate new Worker('file.js') from your main script.
  3. Communicate using postMessage and onmessage.

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.