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:
var worker = new Worker("worker0.js");
More than one worker can be created/loaded by a parent page. This is parallel computing after all :-)
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:
var worker = new Worker("worker0.js");
// String message example
worker.postMessage("Hello");
// Object message example
var personObject = {'firstName': 'Michel', 'lastName':'Buffa'};
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):
onmessage = function (event) {
// do something with event.data
alert('received ' + event.data.firstName);
};
(3) The worker will then send messages back to the parent page (code located in the JavaScript file of the worker):
postMessage("Message from a worker !");
(4) And the parent page can listen to messages from a worker like this:
worker.onmessage = function(event){
// do something with event.data
};
The "Parent HTML page" of a simplistic example using a dedicated Web Worker:
<!DOCTYPE HTML>
<html>
<head>
<title>Worker example: One-core computation</title>
</head>
<body>
<p>The most simple example of Web Workers</p>
<script>
// create a new worker (a thread that will be run in the background)
var worker = new Worker("worker0.js");
// Watch for messages from the worker
worker.onmessage = function(e){
// Do something with the message from the client: e.data
alert("Got message that the background work is finished...")
};
// Send a message to the worker
worker.postMessage("start");
</script>
</body>
</html>
The JavaScript code of the worker (worker0.js):
onmessage = function(e){
if ( e.data === "start" ) {
// Do some computation that can last a few seconds...
// alert the creator of the thread that the job is finished
done();
}
};
function done(){
// Send back the results to the parent page
postMessage("done");
}
The parent page can handle errors that may occur inside its workers, by listening for an onError event from a worker object:
var worker = new Worker('worker.js');
worker.onmessage = function (event) {
// do something with event.data
};
worker.onerror = function (event) {
console.log(event.message, event);
};
}
See also the section "how to debug Web Workers" on next page.