Blog>
Snippets

Optimizing Performance with Web Workers

Show how to offload a heavy computational task to a Web Worker to keep the user interface responsive, highlighting ahead-of-time optimization.
// main.js - Main thread

// Check if Web Workers are supported
if (window.Worker) {
    // Initialize a new Worker
    const myWorker = new Worker('worker.js');

    // Post data to the Worker
    myWorker.postMessage({
        operation: 'heavyComputation',
        data: {/* ... */}
    });

    // Listen for messages from the Worker
    myWorker.onmessage = function(e) {
        console.log('Message received from worker:', e.data);
    };

    // Listen for errors from the Worker
    myWorker.onerror = function(error) {
        console.error('Worker error:', error);
    };
}
else {
    console.error('Your browser does not support Web Workers.');
}
This is the main JavaScript file executed on the main thread. It checks for Web Worker support, initializes a new Worker using an external 'worker.js' file, posts data to the worker for processing, and defines callbacks to handle messages and errors from the Worker.
// worker.js - Web Worker thread

// Respond to message from main thread
self.addEventListener('message', function(e) {
    if (e.data.operation === 'heavyComputation') {
        // Perform heavy computation
        const result = heavyComputation(e.data.data);

        // Post the result back to the main thread
        self.postMessage(result);
    }
});

function heavyComputation(data) {
    // Simulated heavy computation
    // Replace with actual heavy task code
    let sum = 0;
    for (let i = 0; i < 10000000; i++) {
        sum += Math.random();
    }
    return sum;
}
This is the Web Worker file 'worker.js'. It defines an event listener for messages from the main thread. Upon receiving a message with the 'heavyComputation' operation, it performs a heavy computation and then posts the result back to the main thread.