HTML and CSS Reference
In-Depth Information
Shared vs Dedicated Web Workers
The Web Workers we have been using up until this point are called Dedicated Web Workers.
The only script file that is allowed to post messages to the Web Worker is the one that loaded
it. A Shared Web Worker on the other hand can be interacted with from any script that is
loaded from the same origin. This may save on operating system resources if you need to
access a web worker from multiple script files.
Shared Web Workers are not supported by all browsers that currently support Web Workers,
therefore it is worth checking browser support before implementing Shared Web Workers.
Shared Web Workers are instantiated in a similar way to dedicated Web Workers, except the
class name is different:
var worker = new SharedWorker('scripts/tasks-csvparser.js');
The client interaction with Shared Web Workers is also similar to Dedicated Web Workers,
except there is an additional abstraction of a port. Event listeners are added to ports:
and messages are posted to ports
In addition, a port must be explicitly opened before any messages are posted to it:
Finally, the implementation of the Web Worker itself needs to take into account the different
ports. The following is a skeleton for the implementation:
self.addEventListener("connect", function (e) {
var port = e.ports[0];
port.addEventListener("message", function (e) {
var data =;
}, false);
}, false);
Notice that the first event listener we are creating allows general connections to the Web
Worker. When a connection is received for a new port, we then add a separate event listener
for this port, and start the port.
Search WWH ::

Custom Search