Dedicated workers and shared Workers

suggest change

Dedicated Workers

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

Main application:

const worker = new Worker('worker.js');
worker.addEventListener('message', function(msg) {
    console.log('Result from the worker:', msg.data);
});
worker.postMessage([2,3]);

worker.js:

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

Shared Workers

A shared worker is accessible by multiple scripts of the same origin, including other windows, iframes, and 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

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

myWorker.port.postMessage([2,3]);

worker.js

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

    port.onmessage = function(e) {
        console.log('Worker received arguments:', e.data);
        port.postMessage(e.data[0] + e.data[1]);
    }
}

Assigning port.onmessage starts that port, so the worker does not also need port.start(). The page's myWorker.port.start() on the caller is optional for the same reason once onmessage is set.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents