W3C home > Mailing lists > Public > whatwg@whatwg.org > February 2010

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

From: Simon Pieters <simonp@opera.com>
Date: Thu, 25 Feb 2010 09:41:28 +0100
Message-ID: <op.u8oc3e02idj3kv@simon-pieterss-macbook.local>
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

This archive was generated by hypermail 2.4.0 : Wednesday, 22 January 2020 16:59:21 UTC