Home >Web Front-end >JS Tutorial >How to Use JavaScript Shared Web Workers in HTML5
var worker = new SharedWorker("jsworker.js");
var worker = new SharedWorker("jsworker.js"); worker.port.addEventListener("message", function(e) { alert(e.data); }, false); worker.port.start(); // post a message to the shared web worker worker.port.postMessage("Alyssa");When the web worker script receives the first message from a script, it must attach an event handler to the active port. Under most circumstances, the handler will run its own postMessage() method to return a message to the calling code. Finally, the port’s start() method must also be executed to enable messaging: jsworker.js:
var connections = 0; // count active connections self.addEventListener("connect", function (e) { var port = e.ports[0]; connections++; port.addEventListener("message", function (e) { port.postMessage("Hello " + e.data + " (port #" + connections + ")"); }, false); port.start(); }, false);Like their dedicated siblings, shared web workers can:
Shared Workers and Web Workers in JavaScript both allow for multi-threading, but they differ in their scope and usage. A Web Worker is limited to the scope of the tab in which it was created. It cannot communicate with other tabs or windows. On the other hand, a Shared Worker can be accessed from multiple scripts — even those being run on different tabs, windows, or iframes, as long as they are in the same domain. This makes Shared Workers ideal for tasks that require data sharing and communication between different browser contexts.
Creating a Shared Worker in JavaScript involves instantiating the SharedWorker object. Here’s a simple example:
var mySharedWorker = new SharedWorker('worker.js');
In this example, ‘worker.js’ is the script that the Shared Worker will execute. It’s important to note that the script must be on the same domain as the script creating the Shared Worker due to same-origin policy restrictions.
Communication with a Shared Worker is done using the postMessage method and the onmessage event handler. The postMessage method is used to send messages to the Shared Worker, while the onmessage event handler is used to receive messages from it. Here’s an example:
// Sending a message to the Shared Worker
mySharedWorker.port.postMessage('Hello, worker!');
// Receiving a message from the Shared Worker
mySharedWorker.port.onmessage = function(e) {
console.log('Message received from worker: ' e.data);
};
Yes, one of the key features of Shared Workers is their ability to share data between different browser tabs, windows, or iframes. This is possible because all scripts from the same domain have access to the same Shared Worker instance. This makes Shared Workers ideal for tasks that require real-time updates across multiple tabs or windows, such as collaborative editing apps or multi-tab games.
As of now, Shared Workers are supported in most modern browsers, including Google Chrome, Firefox, and Safari. However, they are not supported in Internet Explorer. It’s always a good idea to check the latest browser compatibility information on websites like Can I Use or MDN Web Docs.
Shared Workers have an ‘onerror’ event handler that can be used to catch and handle any errors that occur during their execution. Here’s an example:
mySharedWorker.onerror = function(e) {
console.log('An error occurred: ' e.message);
};
Yes, Shared Workers can make AJAX requests. They have access to the XMLHttpRequest object, which can be used to make asynchronous requests to a server. This allows Shared Workers to fetch data from a server without blocking the main thread, improving the performance of your web application.
Yes, Shared Workers can use WebSockets. This allows them to establish a two-way communication channel with a server, making it possible to send and receive data in real-time without the need for polling.
No, Shared Workers cannot directly access the DOM. This is because they run in a separate thread and do not have access to the same scope as the main thread. However, they can send messages to the main thread, which can then update the DOM based on these messages.
Shared Workers can be terminated by calling the ‘terminate’ method on the SharedWorker object. However, it’s important to note that this will immediately terminate the Shared Worker, regardless of whether it has finished its current task. Here’s an example:
mySharedWorker.terminate();
This will immediately terminate the Shared Worker. It’s generally a good idea to only terminate a Shared Worker if it’s no longer needed or if it’s causing performance issues.
The above is the detailed content of How to Use JavaScript Shared Web Workers in HTML5. For more information, please follow other related articles on the PHP Chinese website!