Thursday, 9 May 2013

HTML5 Web Worker


Oh.. I am fed up with this message. Lots of things to do in JavaScript, but always getting this error.

Have you ever faced this?

I am sure, you might have seen this message at least once in your application. There are many similar situations like a frozen page, partially rendered page etc. And you might have already drilled down into your code and tuned it as is suggested by your architect or lead, though you are not happy to edit your masterpiece. It is the high time to say a NO whenever you are asked to do that. But how?

Multi-threading in JavaScript?

“Cool. But don’t be a joker!”. This would be your response after seeing the heading. But I am serious. Now you can start designing your JavaScript code to bag long running scripts in a spawned thread by keeping the user interface active. Web Worker specification defines an API for running scripts in the background independently of any user interface scripts. So don’t bother about performance tuning!

Let’s jump into..

There are two kinds of workers; dedicated workers and shared workers. Dedicated workers are bound to their creator whereas Shared workers are meant for shared connections. That means, scripts running in the same origin can refer the same worker and communicate with it.

Dedicated worker configuration

test.html

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

worker.js

self.postMessage("Welcome to the world of Web Worker!");
It is a pretty simple worker. It just sends a message back to the main thread using postMessage method. In the context of a worker, both self and this refer the global scope of the worker, you can invoke postMessage of this too.And in the main thread, the messages from spawned thread/worker is intercepted using message event handler (onMessage).
Now, we will see how messages can be sent to worker.

test.html

<!DOCTYPE HTML>
<html>
 <head>
  <title>Example</title>
 </head>
 <body>
  <p id="message"></p>
  <script>
   var worker = new Worker('worker.js');
   worker.onmessage = function (event) {
     document.getElementById('message').textContent = event.data;
   };
   worker.postMessage("start");
  </script>
 </body>
</html>

worker.js

onmessage = function (event){
   if(event.data=="start") {
      postMessage("worker started!");
   }    
};
From worker, if you try to access console or document objects, you will get an ‘Uncaught ReferenceError’ which means that you cant use them.
Here’s a summary of what Web Workers do and don’t have access to.
  • Can use:
    • navigator object
    • location object (read-only)
    • importScripts() method (for accessing script files in the same domain)
    • JavaScript objects such as ObjectArrayDateMathString
    • XMLHttpRequest
    • setTimeout() and setInterval() methods
  • Can’t use:
    • The DOM
    • The worker’s parent page (except via postMessage())

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