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:', 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 — 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
myWorker.port.postMessage([2,3]);
worker.js
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:', e.data);
port.postMessage(e.data[0] + e.data[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.