[whatwg] Combining the DedicatedWorker and SharedWorker interfaces

Jonas Sicking jonas at sicking.cc
Tue Nov 4 14:11:59 PST 2008


> Here's an example in code:
> 
> // dedicated workers (outside)
> var worker = new Worker("foo.js");
> var port = worker.connect();
> port.onmessage = function() { }
> port.postMessage("ping");
> 
> // dedicated workers (inside)
> onconnect = function(e) {
>   e.port.onmessage = function(e) {
>     e.port.postMessage("pong");
>   }
> }
> 
> Shared workers are exactly the same except the constructor is
> SharedWorker("foo.js", "foo");
> 
> Note that I do not think it is necessary to implement this all at
> once. For one, the SharedWorker constructor could easily be punted for
> future releases.
> 
> Thoughts?

My main concern is that I think this makes the most simple use case a 
bit too complicated. In the case when you have a dedicated worker that 
you want to offload some calculations too you need quite a bit of code 
to set up that communication.

With the current API you'd do the following:

main.js:
w = new Worker('worker.js');
w.postMessage(17);
w.onmessage = function(e) {
   answer = e.data;
}

worker.js:
function heavyCalulation(inValue) {
   ...
}
onmessage = function(e) {
   postMessage(heavyCalculation(e.data));
}


With the proposed API:

main.js:
w = new Worker('worker.js');
p = w.connect();
p.postMessage(17);
p.onmessage = function(e) {
   answer = e.data;
}

worker.js:
function heavyCalulation(inValue) {
   ...
}
onconnect = function(e) {
   e.port.onmessage = function(e2) {
     e.port.postMessage(heavyCalulation(e2.data));
   }
}


This complexity I feel is extra bad since I suspect the simple case is 
going to be the common case (I know we disagree there). I especially 
dislike the fact that you have to wait for two events, first a 'connect' 
event and then the actual message event. This seems overly complex for 
the simple case of simply wanting to use a single communication channel 
with a dedicated worker. And even though there isn't that much more code 
in my example above, it took significantly more effort to get it right 
given the nested two handlers that were needed.

So I think we should keep the simple case of a dedicated worker and a 
single communication channel as simple as possible. This means that I 
think we should keep postMessage/onmessage available on the dedicated 
worker directly, as well as the dedicated worker global scope.

As an added bonus this keeps things very similar to message passing 
between windows.


I'm fine with removing things like 'startConversation' and the implicit 
call to connect() on shared workers. 'startConversation' isn't really a 
new communication mechanism, but rather a convenience method on top of 
postMessage.

/ Jonas



More information about the whatwg mailing list