HTML Web Workers

Run background JavaScript scripts without blocking page responsiveness.

When executing scripts in an HTML page, the page becomes unresponsive until the script is finished. A Web Worker is JavaScript running in the background, without affecting the performance of the page.

Web Workers communicate with the main thread using postMessage() and onmessage events.

Key Takeaways: HTML Web Workers

Mastering HTML Web Workers helps you write clean and reliable HTML code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

HTML Web Workers Code Example

HTML
<script>
if (window.Worker) {
  const workerCode = "onmessage = function(e) { postMessage(e.data * 2); };";
  const blob = new Blob([workerCode], {type: "application/javascript"});
  const worker = new Worker(URL.createObjectURL(blob));
  worker.onmessage = (e) => console.log("Result from worker:", e.data);
  worker.postMessage(21);
}
</script>
Output
Result from worker: 42
Free sign-in required · Google login available
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services