Web Workers: typical use

Typical use of Web Workers

1 – A “PARENT HTML5 PAGE” createS workers from a script 

The HTML5 Web Worker API provides the Worker JavaScript interface for loading and executing a script in the background, in a different thread from the UI. The following instruction  loads and creates a worker:

  1. var worker = new Worker(“worker0.js”);

More than one worker can be created/loaded by a parent page. This is parallel computing after all 🙂

2 – You MANAGE A worker by communicating with it using “messages”

Messages can be strings or objects, as long as they can be serialized in JSON format (this is the case for most JavaScript objects, and is handled by the Web Worker implementation of recent browser versions).

Terminology check: serialized 

(1) Messages can be sent by the parent page to a worker using this kind of code:

  1. var worker = new Worker(“worker0.js”);
  2. // String message example
  3. worker.postMessage(“Hello”);
  4. // Object message example
  5. var personObject = {‘firstName’: ‘Michel’, ‘lastName’:‘Buffa’};
  6. worker.postMessage(personObject );

(2) Messages (like the object message example, above) are received from a worker using this method (code located in the JavaScript file of the worker):

  1. onmessage = function (event) {
  2.    // do something with event.data
  3.   alert(‘received ‘ + event.data.firstName);
  4. };

(3) The worker will then send messages back to the parent page  (code located in the JavaScript file of the worker):

  1. postMessage(“Message from a worker !”);

(4) And the parent page can listen to messages from a worker like this:

  1. worker.onmessage = function(event){
  2.     // do something with event.data
  3. };

3 – a complete example

The “Parent HTML page” of a simplistic example using a dedicated Web Worker:

  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <title>Worker example: One-core computation</title>
  5. </head>
  6. <body>
  7. <p>The most simple example of Web Workers</p>
  8.    // create a new worker (a thread that will be run in the background)
  9.    var worker = new Worker(“worker0.js”);
  10.    // Watch for messages from the worker
  11.    worker.onmessage = function(e){
  12.      // Do something with the message from the client: e.data
  13.      alert(“Got message that the background work is finished…”)
  14.    };
  15.    // Send a message to the worker
  16.    worker.postMessage(“start”);
  17. </body>
  18. </html>

The JavaScript code of the worker (worker0.js):

  1. onmessage = function(e){
  2.    if ( e.data === “start” ) {
  3.       // Do some computation that can last a few seconds…
  4.       // alert the creator of the thread that the job is finished
  5.       done();
  6.     }
  7. };
  8. function done(){
  9.     // Send back the results to the parent page
  10.     postMessage(“done”);
  11. }

4 – Handling errors

The parent page can handle errors that may occur inside its workers, by listening for an onError event from a worker object:

  1. var worker = new Worker(‘worker.js’);
  2. worker.onmessage = function (event) {
  3.     // do something with event.data
  4. };
  5. worker.onerror = function (event) {
  6.     console.log(event.message, event);
  7. };
  8. }

See also the section “how to debug Web Workers”…

Leave a comment