iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

HTML Web Workers

Web Workers run JavaScript on a background thread so the main UI thread stays responsive. Use them for CPU-heavy work like parsing, image processing, or crypto.

Web Workers in practice

EXAMPLE
<!-- index.html -->
<button id='go'>Start heavy work</button>
<output id='result'></output>

<script>
  // Spawn a worker from a separate JS file
  const worker = new Worker('/worker.js', { type: 'module' });

  document.getElementById('go').addEventListener('click', () => {
    worker.postMessage({ type: 'fib', n: 42 });
  });

  worker.addEventListener('message', (e) => {
    document.getElementById('result').textContent =
      \`fib(${e.data.n}) = ${e.data.value} (took ${e.data.ms} ms)\`;
  });

  worker.addEventListener('error', (e) => {
    console.error('worker error', e.message);
  });
</script>


<!-- worker.js -->
// Worker has its own global scope: 'self', no DOM access
self.addEventListener('message', (e) => {
  if (e.data.type === 'fib') {
    const start = performance.now();
    const value = fib(e.data.n);
    const ms = Math.round(performance.now() - start);
    self.postMessage({ n: e.data.n, value, ms });
  }
});

function fib(n) {
  return n < 2 ? n : fib(n - 1) + fib(n - 2);
}


// Pass transferable objects to avoid copying big buffers
const buf = new ArrayBuffer(1024 * 1024);
worker.postMessage({ buf }, [buf]);   // buf is detached on the main thread


// Stop a worker
worker.terminate();


// Inline workers via Blob URL (for small experiments)
const code = \`onmessage = (e) => postMessage(e.data.toUpperCase());\`;
const blob = new Blob([code], { type: 'text/javascript' });
const url  = URL.createObjectURL(blob);
const w    = new Worker(url);


// Shared Worker - many tabs share the same instance
const shared = new SharedWorker('/shared-worker.js');
shared.port.start();
shared.port.postMessage('hello');

Why it matters

Web Workers are the cure for jank in CPU-heavy apps. Move parsing, encoding, image manipulation, and crypto off the main thread. For very common patterns, libraries like Comlink make the postMessage dance feel like normal function calls.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
<!DOCTYPE html>
<html>
<head>
    <title>HTML Web Workers</title>
</head>
<body>

<h1>HTML Web Workers</h1>
<p>This is a demo page for the "HTML Web Workers" lesson.</p>

</body>
</html>
Try it Yourself »

Exercise

Spin up a background worker from a script file.

const w = new ('worker.js');

Test yourself

Q1. Web Workers run JavaScript on…
Q2. Workers can NOT access…
Q3. Workers communicate with…

Discussion

Loading…