Web Workers in a Nutshell
A web worker is a single JavaScript file loaded and executed in the background on a separate thread. Dedicated web workers are linked to their creator (the script which loaded the worker). Shared web workers allow any number of scripts to communicate with a single worker. Shared web workers adhere to the same rules as their dedicated counterparts: no DOM, document or page script access, and limited read-only permission to most window properties. In addition, page scripts may only communicate with shared web workers from the same origin/domain (somesite.com). Currently, shared web workers are supported in Chrome, Safari and Opera. Firefox 4 and IE9 support may arrive, but don’t bet on it. Shared workers may save resources but they add an extra level of complexity. Expect a few issues, e.g.,- DOM2 events (addEventListener) handlers appear to be the most reliable implementation.
- You’ll almost certainly encounter browser-specific quirks and debugging is difficult. The following code works in the latest version of Chrome, but don’t assume it’ll work in Safari or Opera.
Creating a Shared Web Worker
To create a shared web worker, you pass a JavaScript file name to a new instance of the SharedWorker object:var worker = new SharedWorker("jsworker.js");
Communicating with a Shared Web Worker
Any of your page scripts can communicate with the shared web worker. Unlike dedicated web workers, you must communicate via a ‘port’ object and attach a message event handler. In addition, you must call the port’s start() method before using the first postMessage(): pagescript.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:
- load further scripts with importScripts()
- attach error handlers, and
- run the port.close() method to prevent further communication on a specific port.
Frequently Asked Questions (FAQs) about JavaScript Shared Web Workers
What is the main difference between Shared Workers and Web Workers in JavaScript?
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.
How do I create a Shared Worker in JavaScript?
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.
How can I communicate with a Shared Worker?
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);
};
Can Shared Workers share data between different browser tabs?
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.
Are Shared Workers supported in all browsers?
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.
How can I handle errors in Shared Workers?
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);
};
Can Shared Workers make AJAX requests?
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.
Can Shared Workers use WebSockets?
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.
Can Shared Workers access the DOM?
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.
How can I terminate a Shared Worker?
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!

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor

WebStorm Mac version
Useful JavaScript development tools
