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>