Table of Contents
Web Workers in a Nutshell
Creating a Shared Web Worker
Communicating with a Shared Web Worker
Frequently Asked Questions (FAQs) about JavaScript Shared Web Workers
What is the main difference between Shared Workers and Web Workers in JavaScript?
How do I create a Shared Worker in JavaScript?
How can I communicate with a Shared Worker?
Can Shared Workers share data between different browser tabs?
Are Shared Workers supported in all browsers?
How can I handle errors in Shared Workers?
Can Shared Workers make AJAX requests?
Can Shared Workers use WebSockets?
Can Shared Workers access the DOM?
How can I terminate a Shared Worker?
Home Web Front-end JS Tutorial How to Use JavaScript Shared Web Workers in HTML5

How to Use JavaScript Shared Web Workers in HTML5

Mar 04, 2025 am 01:01 AM

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");
Copy after login

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");
Copy after login
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);
Copy after login
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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles