Move CPU-heavy work away from the main thread.
- Worker
- postMessage
- structured clone
- termination
A Web Worker runs JavaScript on a separate thread and communicates by messages. It cannot directly manipulate the page DOM. Send work and results as data, terminate workers when no longer needed, and measure whether the transfer cost is worthwhile. For tiny work, staying on the main thread can be simpler.
Moving a task to a worker does not make an inefficient algorithm efficient; it mainly protects responsiveness.
Run a CPU-heavy calculation in a worker and compare page responsiveness.
Open example.html in a browser and edit example.js. Save, refresh, and use the Console and debugger to inspect values.
- Explain the core idea in your own words without reading the code.
- Change one input and predict the output before running it.
- Test one boundary or failure case, then record what you changed.
Run python3 -m http.server 8000 from the JavaScripts folder, then open this lesson through http://localhost:8000/. Fetch, modules, storage, history, and workers can behave differently or fail under file URLs.