Jump to content

Featured Replies

Posted

You are reading Part 28 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 5]

Introduction

JavaScript is single-threaded by default, meaning it executes code sequentially in a single thread. However, for CPU-intensive tasks, Web Workers allow JavaScript to run code in parallel threads, improving performance and responsiveness.

1. Understanding Web Workers

Web Workers enable JavaScript to run scripts in the background, separate from the main thread, preventing UI freezes.

Types of Web Workers:

  1. Dedicated Workers – Each worker has its own script and is used by a single script.

  2. Shared Workers – Can be accessed by multiple scripts across different browser contexts (e.g., iframes, tabs).

  3. Service Workers – Used for caching, push notifications, and background sync.

2. Creating a Web Worker

A Dedicated Web Worker is created using the Worker constructor.

Step 1: Create a Worker Script (worker.js)

self.onmessage = function(event) {
    let result = event.data * 2; // Process data
    self.postMessage(result); // Send data back
};

Step 2: Initialize the Worker in the Main Thread

let worker = new Worker("worker.js");
worker.postMessage(10); // Send data to worker

worker.onmessage = function(event) {
    console.log("Received from worker:", event.data);
};

3. Web Workers vs Main Thread Execution

Using Web Workers prevents blocking the UI thread. For example:

Without Web Workers (Blocking UI Thread)

function compute() {
    let sum = 0;
    for (let i = 0; i < 1e9; i++) {
        sum += i;
    }
    console.log("Computation Done:", sum);
}
compute(); // UI will freeze during execution

With Web Workers (Non-Blocking Execution)

let worker = new Worker("worker.js");
worker.postMessage("start"); // Moves computation to a separate thread

4. Communication Between Main Thread and Web Workers

Web Workers use the postMessage API for communication.

Sending Data to a Worker

worker.postMessage({ task: "calculate", value: 50 });

Receiving Data from a Worker

worker.onmessage = function(event) {
    console.log("Result from worker:", event.data);
};

5. Terminating a Web Worker

To stop a worker manually, use worker.terminate().

worker.terminate();

Inside the worker, it can self-terminate using:

self.close();

6. Shared Workers (Multiple Scripts Using the Same Worker)

Shared Workers allow multiple browser contexts (e.g., different tabs) to communicate with a single worker.

Creating a Shared Worker (shared-worker.js)

self.onconnect = function(event) {
    let port = event.ports[0];
    port.onmessage = function(e) {
        port.postMessage("Received: " + e.data);
    };
};

Connecting to a Shared Worker

let sharedWorker = new SharedWorker("shared-worker.js");
sharedWorker.port.postMessage("Hello Worker");
sharedWorker.port.onmessage = function(event) {
    console.log(event.data);
};

7. Service Workers (For Background Sync & Caching)

Service Workers run separately from the web page and enable caching, push notifications, and offline functionality.

Registering a Service Worker

if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register("service-worker.js")
        .then(reg => console.log("Service Worker Registered"))
        .catch(err => console.error("Service Worker Failed:", err));
}

8. When to Use Web Workers?

Use Case

Best Choice

Heavy computations (e.g., large loops, encryption)

Dedicated Worker

Sharing data across multiple tabs

Shared Worker

Background caching & push notifications

Service Worker

You are reading Part 28 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 5]

  • Views 30
  • Created
  • Last Reply

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

Important Information

Terms of Use Privacy Policy Guidelines We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.