← Back to HTML Course | Chapter 7: Advanced APIs & Features | Lesson 6 of 11

HTML Web Workers

Imagine running a busy restaurant kitchen. If you are the only chef, you have to take the order, cook the food, wash the dishes, and clean the tables all by yourself. If a customer orders a complex dish that takes an hour to prep, everything else stops, and other customers get frustrated. Now, imagine hiring a prep cook (a Web Worker). You can hand them the complex, slow prep work to handle in the back room while you focus on plating and serving dishes quickly. An HTML Web Worker does exactly that. It is a background script that runs in the background, allowing your webpage to handle complex tasks (like analyzing text or compressing files) without freezing your user interface.

Understanding Multi-Threaded Browsing

Web browsers normally run all scripts on a single main thread, which also handles page rendering and user interactions. If a script runs a heavy, complex task, the main thread freezes, making the page unresponsive.

Note: Use Web Workers to offload heavy calculations and keep your page smooth and responsive.

Warning: Web Workers cannot access the webpage DOM or window objects directly; they communicate solely via messages.

Example: Understanding Multi-Threaded Browsing

markup
<script>
  // Without a worker, a heavy loop here would freeze the page
  const worker = new Worker('worker.js');
</script>

Creating a Web Worker

To create a Web Worker, you initialize a new Worker object inside your main script, pointing to a separate JavaScript file that contains the code you want to run in the background.

Note: Save your background worker code in a separate file named worker.js inside your project.

Warning: Make sure your worker file path is correct, as broken links will prevent the worker from initializing.

Example: Creating a Web Worker

markup
<script>
  const worker = new Worker('worker.js');
</script>

Exchanging Messages (postMessage)

Because Web Workers run on a separate thread, they cannot modify your page elements directly. Instead, they communicate with your main script by sending messages back and forth using the postMessage method and listening with the onmessage event.

Note: Use postMessage to pass data inputs to your worker, and let the worker return the calculated results when finished.

Warning: Always write clear message handlers in both your main script and your worker file to manage data flow.

Example: Exchanging Messages (postMessage)

markup
<script>
  const worker = new Worker('worker.js');
  worker.postMessage('start');
  worker.onmessage = function (event) {
    console.log('Result:', event.data);
  };
</script>

Terminating Worker Threads

Web Workers consume system memory and CPU resources while running. To keep your app performing well, you should always terminate workers once they finish their tasks using the terminate method from your main script, or close inside the worker itself.

Note: Terminate background workers immediately once they finish their tasks to free up device memory.

Warning: Once a worker is terminated, it cannot be restarted; you must spawn a new worker instance to run tasks again.

Example: Terminating Worker Threads

markup
<script>
  const worker = new Worker('worker.js');
  worker.terminate();
</script>

Web Worker Constraints

Because Web Workers run on a separate background thread, they have some strict limitations: they cannot access the DOM, the window object, or local page elements, and must load external scripts using the importScripts method.

Note: Use Web Workers strictly for processing raw data and calculations, and use your main script to update page layouts.

Warning: Web Worker files must comply with Cross-Origin Resource Sharing (CORS) rules, or the browser will block them.

Example: Web Worker Constraints

markup
<script>
  const worker = new Worker('worker.js');
  worker.postMessage('data');
  // worker.js cannot access document or window directly
</script>
Common Mistakes
  1. Attempting to modify webpage elements or access the DOM directly from your background worker files.
  2. Forgetting to terminate background workers, which wastes system memory and slows down devices.
  3. Using incorrect file paths when initializing workers, causing loading errors.
Chapter Summary
  • Web Workers run background scripts on separate threads to keep your main webpage smooth and responsive.
  • Web Workers communicate with your main scripts by sending messages back and forth using the postMessage method.
  • Workers cannot access webpage elements directly, and should be terminated once they finish their tasks to free up device memory.
Browser Support

Standard HTML5 Web Workers are supported natively by all modern web browsers.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.