[whatwg] Web Workers: include simple example for shared workers

On Tue, 23 Feb 2010 21:36:15 +0100, Simon Pieters <simonp at opera.com> wrote:

> step 3.
>
> test.html
> <pre id="log">Log:</pre>
> <script>
> var worker = new SharedWorker('test.js');
> var log = document.getElementById('log');
> worker.port.addEventListener('message', function(e) {
>    log.textContent += '\n' + e.data;
> }, false);
> worker.port.start();
> worker.port.postMessage('ping');
> </script>
> <iframe src=other.html></iframe>
>
> other.html
> <pre id=log>Inner log:</pre>
> <script>
> var worker = new SharedWorker('test.js');
> var log = document.getElementById('log');
> worker.port.onmessage = function(e) {
>    log.textContent += '\n' + e.data;
> }
> </script>
>
> test.js
> onconnect = function(e) {
>    var port = e.ports[0];
>    port.postMessage('hello');
>    port.onmessage = function(e) {
>      port.postMessage('pong');
>    }
> }

The worker script could be modified in step 3 as follows to make it clear  
that the script is in fact shared:

test.js
var i = 0;
onconnect = function(e) {
   i++;
   var port = e.ports[0];
   port.postMessage('hello, ' + i);
   port.onmessage = function(e) {
     port.postMessage('pong');
   }
}

-- 
Simon Pieters
Opera Software

Received on Thursday, 25 February 2010 00:41:28 UTC