Bhylu

Web Workers API

A Web Worker runs JavaScript in a separate execution context so computation need not block page interaction. The page and worker communicate through messages rather than sharing the document tree.

How it works

  • A worker has no document or direct access to the page’s DOM. It sends results back so the page can update the interface.
  • postMessage passes structured-cloneable values; large data copies can still be expensive. Some buffers can be transferred deliberately.
  • Terminate a worker when its task is finished or cancelled. Your site’s CSP and origin rules must permit the worker source.

A practical example

HTML

<p id="worker-result" role="status">Calculating…</p>
<script>
  const source = "self.onmessage = event => self.postMessage(event.data * 2);";
  const url = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }));
  const worker = new Worker(url);
  worker.onmessage = event => {
    document.getElementById('worker-result').textContent = 'Result: ' + event.data;
    worker.terminate();
    URL.revokeObjectURL(url);
  };
  worker.onerror = () => { worker.terminate(); URL.revokeObjectURL(url); };
  worker.postMessage(21);
</script>

In a normal page whose policy permits blob workers, the worker doubles 21 and sends back 42. Only the page-side handler touches the paragraph.