HTML Web Workers
In this page:
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
<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
<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)
<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
<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
<script>
const worker = new Worker('worker.js');
worker.postMessage('data');
// worker.js cannot access document or window directly
</script>
- Attempting to modify webpage elements or access the DOM directly from your background worker files.
- Forgetting to terminate background workers, which wastes system memory and slows down devices.
- Using incorrect file paths when initializing workers, causing loading errors.
- 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.
Standard HTML5 Web Workers are supported natively by all modern web browsers.
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: