HTML APIs

Explain Web Worker in HTML

A Web Worker runs JavaScript on a background thread, so heavy computation happens off the main thread and the user interface stays smooth and responsive.


What is a Web Worker?

JavaScript in the browser normally runs on a single main thread that also handles rendering and user input. If a script does heavy work - parsing a large file, image processing, complex maths - the whole page freezes until it finishes. A Web Worker solves this by running a separate script on its own OS-level background thread, in parallel with the main thread.

Because the worker runs elsewhere, long-running tasks no longer block scrolling, clicks or animations. The main thread and the worker communicate by passing messages back and forth.

Creating a worker

You create a dedicated worker with new Worker(url), pointing to a separate JavaScript file. The two threads talk using postMessage() to send data and the onmessage handler (or a 'message' event listener) to receive it.

worker.js - runs on the background thread
// worker.js
self.onmessage = (event) => {
  const n = event.data;

  // A deliberately heavy computation
  let sum = 0;
  for (let i = 0; i < n; i++) {
    sum += Math.sqrt(i);
  }

  // Send the result back to the main thread
  self.postMessage(sum);
};
main page - stays responsive while the worker runs
<button id="run">Compute</button>
<p id="result">Idle</p>

<script>
  if (window.Worker) {
    const worker = new Worker("worker.js");

    document.getElementById("run").addEventListener("click", () => {
      document.getElementById("result").textContent = "Working...";
      worker.postMessage(1e8); // send a number to the worker
    });

    worker.onmessage = (event) => {
      document.getElementById("result").textContent = "Result: " + event.data;
    };

    worker.onerror = (err) => console.error("Worker error:", err.message);

    // worker.terminate();  // stop the worker when no longer needed
  } else {
    document.getElementById("result").textContent = "Web Workers not supported.";
  }
</script>

How communication works

Data passed through postMessage() is copied using the structured clone algorithm, not shared by reference - so the two threads never share mutable state directly. You can pass numbers, strings, arrays, objects, ArrayBuffers and more. Large buffers can be transferred (moved rather than copied) for performance using the transfer list argument.

Limitations: no DOM access

A worker runs in a stripped-down global scope (WorkerGlobalScope), not the window. This is what it cannot do:

  • No access to the DOM - it cannot touch document, or read/change the page's HTML elements.
  • No access to window, parent or the page's global variables.
  • It CAN use fetch, XMLHttpRequest, WebSockets, setTimeout/setInterval, IndexedDB and importScripts().
  • To change the UI, send a message back to the main thread and let that thread update the DOM.
  • The worker file must be served from the same origin (subject to CORS).
ℹ️

Web Workers are supported in all modern browsers. Beyond the dedicated worker shown here, there are Shared Workers (shared by multiple tabs of one origin) and Service Workers (a specialised worker for caching, offline support and push, sitting between the page and the network).

💡

Always call worker.terminate() (or self.close() inside the worker) when the task is done. Idle workers keep their thread alive and consume memory. Reuse one long-lived worker for repeated tasks rather than spawning a new one each time.

Ready to use your HTML skills?

Find web development internships and fresher jobs across India.

Browse Web Dev Internships