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.
- Shared State: They allow shared state or data across multiple browser contexts.
- Resource Efficiency: They avoid creating multiple worker instances, thus saving resources.
- Inter-Window Communication: They enable communication between different windows, iframes, or tabs.
To use a Shared Worker, you need to create a worker script and then instantiate the Shared Worker in your main scripts.
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();
});Now, instantiate and use the Shared Worker in your main script files (these could be in different windows, iframes, or tabs).
// 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.
-
Shared Worker Script:
- The
connectevent is fired when a connection is made from a browsing context. - Each connection has its own
MessagePortwhich is used for communication. - Messages sent to the worker are broadcasted to all connected contexts.
- The
-
Main Script:
- Instantiate the
SharedWorkerwith 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.
- Instantiate the
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.
- Same-Origin Policy: Shared Workers are bound by the same-origin policy, meaning they can only be accessed by scripts from the same origin.
- Lifecycle: The Shared Worker remains active as long as there is at least one connection. It will be terminated when all connections are closed.
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.