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.
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:
connect
event is fired when a connection is made from a browsing context.MessagePort
which is used for communication.Main Script:
SharedWorker
with the path to the worker script.port.addEventListener
.port.start()
to begin listening for messages.port.postMessage
.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.
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.