javascript / expert
Snippet
Computational Offloading via Web Workers in Angular
To keep the UI responsive during intensive calculations (e.g., data processing or image manipulation), Angular can offload tasks to Web Workers. This moves the computation to a background thread, preventing the main thread from freezing and ensuring smooth change detection and animations.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
computeHeavyTask() {if (typeof Worker !== 'undefined') {const worker = new Worker(new URL('./app.worker', import.meta.url));worker.onmessage = ({ data }) => {this.result = data;worker.terminate();};worker.postMessage(this.inputData);} else {// Fallback logic for environments without Web Workers}}
angular
Breakdown
1
new Worker(new URL('./app.worker', import.meta.url));
Creates a new Web Worker instance using a relative path, compatible with Angular's build system (Webpack/Esbuild).
2
worker.onmessage = ({ data }) => {
Sets up a listener to receive the computed result from the worker thread asynchronously.
3
worker.postMessage(this.inputData);
Sends data to the worker thread to initiate the background computation.