Html5 Tutorial : Web Workers

Forums » Bookshelf » Html5 Tutorial » Web Workers

10. HTML5 Web Workers

10.1. The Current JavaScript Execution Model

  • As a developer or as a user, you might have already encountered an error saying that a JavaScript script is taking too much time to run (also called unresponsive script…), why is that?
  • JavaScript runs in single-threaded environment.

    • While a long operation is taking place, the application becomes unresponsive to user interaction.

      [Note]Note

      Many browsers might think that something is going wrong if a task is taking too much time and they will propose you to kill the script.

    • To circumvent that, most developers used to break a big operation into smaller ones when possible and use setTimeout or setInterval for instance.
  • The arrival of web workers will now allow developers to run an other script independent from the user interface script in a web application.

10.2. Introduction To Web Workers

  • Like many features labelled HTML5, web worker is not part of the HTML5 specification but since it contributes to build better application, we are going to describe it.

  • What is a web worker?

    • A worker is a thread, it allows you to perform tasks in a background process in parallel of the main browser process.
    • A worker is a JavaScript file that contains the "tasks" you want to perform in a separate thread.
  • Be careful though, we cannot access everything we want in a worker. Below is what we can access:

    • navigator object.
    • location object (read-only).
    • importScripts() method allows you access to script files in the same domain.
    • JavaScript objects such as Object, Array, Date, Math, String.
    • XMLHttpRequest object.
    • setTimeout() and setInterval() methods.

      [Note]Note

      We do not have access to the DOM inside a Worker and we do not have access to the page that spawned this same Worker.

10.3. Usage Of Web Workers

  • According to the specification:

     

    Workers (as these background scripts are called herein) are relatively heavy-weight, and are not intended to be used in large numbers. … Generally, workers are expected to be long-lived, have a high start-up performance cost, and a high per-instance memory cost.

     
     -- Web Workers specification http://www.w3.org/TR/workers/#scope
  • Knowing that, when would it be a good fit to use web workers? Generally they are used for scripts that are taking a long time. That could be for instance:

    • The classic example you can find on internet ⇒ calculate prime numbers.
    • To do operations on a client-side database.
    • Parse a large JSON string.
    • Image or video processing.
    • Etc…

10.4. Communication APIs

  • To spawn a new worker:

    var robot=new Worker('robot.js');
  • To send a message between the main thread and the worker and vice versa we will use the postMessage method. For instance, to send a message to the worker:

    robot.postMessage(msg_for_worker);
  • To receive the message, we need to subscribe to the message event. For instance, for the worker to receive messages from the main thread:

    self.onmessage=function(event){
      //Do something
    };
    [Note]Note

    The actual message itself is contained in event.data

10.5. Handling Errors

  • Inside a worker, you can register to the error event like this:

    self.onerror=function(error){
      //Do something
    };
  • The ErrorEvent interface which is passed as a parameter to the the error event handler contains the following informations:

    • filename: Name of the worker that caused the error
    • lineno: Line number where the error occurred
    • message: The error message

10.6. Browser Support

  • Web workers are currently supported on Firefox 3.5+, Safari 4.0+, Chrome 6.0+ and Opera 10.6+

10.7. Quiz

  1. What can cause an unresponsive script in a browser?
  2. You can access the DOM of the page that spawned the worker in the worker?

    • True
    • False
  3. Cite 2 use case of using web workers
  4. What is the method used to communicate between the main UI thread and the worker?

    • sendMessage(msg)
    • sendMsg(msg)
    • postMessage(msg)
    • postMsg(msg)