search
HomeWeb Front-endJS TutorialHow to Use JavaScript Shared Web Workers in HTML5

How to Use JavaScript Shared Web Workers in HTML5

How to Use JavaScript Shared Web Workers in HTML5

We recently discussed JavaScript web workers with reference to the “dedicated” variety. If you’ve not read it yet, I suggest you do that first — this article builds on the same concepts.

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.
Shared web workers probably won’t be a viable technology for a couple of years, but they raise exciting opportunities for the future of JavaScript development. Let’s hope browser vendors can supply a few decent tracing and debugging tools!

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

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.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

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.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

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 of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

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.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

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.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

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's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

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: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

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.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools