Performance: Web workers for heavy computation
This concept affects the page's input responsiveness and smoothness by offloading heavy tasks from the main thread.
Jump into concepts and practice - no test required
const worker = new Worker(new URL('./heavy.worker.ts', import.meta.url)); worker.postMessage('start'); worker.onmessage = ({ data }) => { console.log('Result:', data); };
function heavyCalculation() { let result = 0; for (let i = 0; i < 1e9; i++) { result += i; } return result; } heavyCalculation();
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy computation on main thread | N/A | Blocks reflows during computation | Delays paint and composite | [X] Bad |
| Heavy computation in web worker | N/A | No blocking of reflows | Paint and composite proceed smoothly | [OK] Good |
Web Workers in an Angular application?compute?ng generate worker <name>.ng generate worker compute.const worker = new Worker(new URL('./compute.worker', import.meta.url));
worker.onmessage = ({ data }) => console.log('Result:', data);
worker.postMessage(10);postMessage(10).postMessage.onmessage handler logs 'Result: 20'.const worker = new Worker('./compute.worker');
worker.onmessage = (event) => console.log(event.data);
worker.postMessage(5);new URL('./compute.worker', import.meta.url) for correct bundling.1. Create a worker with Angular CLI.
2. Send the large array to the worker usingpostMessage.
3. In the worker, process the array and send back the result.
4. Update the UI with the result when received.