Thursday, 9 May 2013

HTML5 Shared Worker

In the last blog, we have seen how dedicated web workers are implemented in HTML5. This blog is about another worker category which is called Shared Worker.

Shared worker configuration

test1.html

<!DOCTYPE HTML>
<title>Shared worker Example</title>
<p id="message"></p>
<script>
  var worker = new SharedWorker('sharedworker.js');
  var message = document.getElementById('message');
  worker.port.onmessage = function(event) { 
    message.textContent = event.data;
  }
</script>

sharedworker.js

onconnect = function(e) {
  var port = e.ports[0];
  port.postMessage('Welcome to Shared Worker programming!');
}
Now we will see, how 2 different pages connect to the same worker. To test that, you can add test2.html by including sharedworker.js, in the same way as done in test1.html.
The WorkerGlobalScope common interface

interface WorkerGlobalScope : EventTarget {
  readonly attribute WorkerGlobalScope self;
  readonly attribute WorkerLocation location;

  void close();
           attribute EventHandler onerror;
           attribute EventHandler onoffline;
           attribute EventHandler ononline;
};
WorkerGlobalScope implements WorkerUtils;
location will return the absolute URL of the script that was used to initialize the worker.
error event can be used to handle all errors.
 worker.onerror = function(error) {
      console.log("Error is caught "+error.message);
      throw error;
    };
Shared worker can be used to have a client to client communication since the worker data is shared across all the clients.

References

  1. http://www.whatwg.org/specs/web-apps/current-work/multipage/workers.html#workers
  2. https://developer.mozilla.org/en-US/docs/DOM/Using_web_workers?redirectlocale=en-US&redirectslug=Using_web_workers
  3. http://dev.opera.com/articles/view/web-workers-rise-up/

No comments:

Post a Comment