In my previous post, I discussed how Web Workers can be used to enhance the responsiveness of web applications by offloading resource-intensive computations to run in the background, thus preventing them from blocking the main thread. Today, let's look into Shared Web Workers and how they can further boost your app's efficiency.
Shared Web Workers are a special type of Web Worker that can be accessed from multiple browsing contexts, such as different tabs, windows, or iframes. This shared access can facilitate various functionalities, including real-time communication, managing shared state, and caching data across multiple tabs or windows. By reusing a single worker instance, Shared Web Workers help reduce memory consumption and improve performance compared to creating a new worker for each context.
The following example shows the basics of using a Shared Web Worker.
1. Create the Shared Web Worker Script
Shared Web Workers use ports to communicate. You need to handle the onconnect
event to establish communication with the port and the onmessage
event to process incoming messages.
// worker.js onconnect = (event) => { const port = event.ports[0]; port.onmessage = (e) => { port.postMessage(e.data[0] + e.data[1]); }; };
2. Use the Shared Web Worker in Your Main Script
In your main script, initialise the Shared Web Worker. This can be done from multiple scripts or HTML pages. Once created, any script running on the same origin can access the worker and communicate with it. The various scripts will use the same worker for tasks, even if they are running in different windows.
<html> <head/> <body> <h1>Shared Web Worker Example</h1> <p id="result">Computing...</p> <script> const worker = new SharedWorker('path/to/worker.js'); worker.port.onmessage = (e) => { document.getElementById('result').textContent = `Result: ${e.data}`; }; worker.port.postMessage([1, 2]); </script> </body> </html>
Communication between the main script and the Shared Web Worker is done using the port.postMessage
method to send messages and the port.onmessage
event to receive messages.
Related posts:
Web Workers
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.