HTML Web Workers
In this page:
const worker = new Worker("worker.js");
worker.postMessage(data);
worker.onmessage = (event) => { /* event.data */ };
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.
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.
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.
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.
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.
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: