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
        operation: 'heavyComputation',
        data: {/* ... */}

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

    // 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 ( === 'heavyComputation') {
        // Perform heavy computation
        const result = heavyComputation(;

        // Post the result back to the main thread

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.