JavaScript Workers Dedicated Workers and Shared Workers


Dedicated Workers

A dedicated web worker is only accessible by the script that called it.

Main application:

var worker = new Worker('worker.js');
worker.addEventListener('message', function(msg) {
    console.log('Result from the worker:',;


self.addEventListener('message', function(msg) {
    console.log('Worker received arguments:',;
    self.postMessage([0] +[1]);

Shared Workers

A shared worker is accessible by multiple scripts — even if they are being accessed by different windows, iframes or even workers.

Creating a shared worker is very similar to how to create a dedicated one, but instead of the straight-forward communication between the main thread and the worker thread, you'll have to communicate via a port object, i.e., an explicit port has to be opened so multiple scripts can use it to communicate with the shared worker. (Note that dedicated workers do this implicitly)

Main application

var myWorker = new SharedWorker('worker.js');
myWorker.port.start();  // open the port connection



self.port.start(); open the port connection to enable two-way communication

self.onconnect = function(e) {
    var port = e.ports[0];  // get the port

    port.onmessage = function(e) {
        console.log('Worker revceived arguemnts:',;
        port.postMessage([0] +[1]);

Note that setting up this message handler in the worker thread also implicitly opens the port connection back to the parent thread, so the call to port.start() is not actually needed, as noted above.