jsnotes

Topic 007: Shared workers in JS

Topic 007: Shared workers in JS

A Shared Worker in JavaScript allows multiple scripts (potentially from different windows, iframes, or even tabs) to communicate with a single worker. This is useful for scenarios where you need to share data or manage state across different parts of your web application.

Key Features of Shared Workers:

  1. Shared State: They allow shared state or data across multiple browser contexts.
  2. Resource Efficiency: They avoid creating multiple worker instances, thus saving resources.
  3. Inter-Window Communication: They enable communication between different windows, iframes, or tabs.

Creating and Using a Shared Worker

To use a Shared Worker, you need to create a worker script and then instantiate the Shared Worker in your main scripts.

Example: Creating a Shared Worker Script

Create a new file shared-worker.js:

// shared-worker.js
const connections = [];

self.addEventListener("connect", (event) => {
  const port = event.ports[0];
  connections.push(port);

  port.addEventListener("message", (event) => {
    console.log("Received message from main script:", event.data);

    // Broadcast the message to all connected contexts
    connections.forEach((connection) => {
      connection.postMessage(`Broadcast: ${event.data}`);
    });
  });

  port.start();
});

Using the Shared Worker in Different Contexts

Now, instantiate and use the Shared Worker in your main script files (these could be in different windows, iframes, or tabs).

Example: Main Script (index.js)

// index.js
const worker = new SharedWorker("shared-worker.js");

worker.port.addEventListener("message", (event) => {
  console.log("Received message from shared worker:", event.data);
});

worker.port.start();

// Send a message to the shared worker
worker.port.postMessage("Hello from the main script");

You can repeat the above instantiation code in different scripts that may run in other windows, iframes, or tabs to share the same worker.

Detailed Explanation:

  1. Shared Worker Script:

    • The connect event is fired when a connection is made from a browsing context.
    • Each connection has its own MessagePort which is used for communication.
    • Messages sent to the worker are broadcasted to all connected contexts.
  2. Main Script:

    • Instantiate the SharedWorker with the path to the worker script.
    • Listen for messages from the worker using port.addEventListener.
    • Start the port using port.start() to begin listening for messages.
    • Send messages to the worker using port.postMessage.

Use Case: Chat Application

Imagine a simple chat application where multiple tabs or windows need to share messages. Using a Shared Worker, you can broadcast messages to all open tabs.

Additional Notes:

Shared Workers provide a powerful way to share data and state across multiple parts of your web application, leading to more efficient resource usage and better synchronization between different contexts.