How to Use JavaScript Shared Web Workers in HTML5

Share this article

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.

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

javascriptworkers
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week