Lesson 2: Working with web workers CHAPTER 9 405
This HTML page has a reference to jQuery and a default.js file. The default.js file has code
to create a new web worker by calling the Worker() constructor and passing the URI of a
script to execute. You can receive notifications from the web worker by setting the onmessage
and the onerror properties to an event handler function, as shown in the following example.
/// <reference path="Scripts/jquery-1.8.2.js" />
var worker = new Worker('myWork.js');
worker.onmessage = function (e) {
$('#result').append(e.data + '<br />');
}
worker.onerror = function (e) {
$('#result').append('Error: ' + e.data + '<br />');
}
$('document').ready(function () {
$('#btnSend').on('click', function () {
worker.postMessage($('#message').val());
});
});
The web worker code is in the myWork.js file. This example also shows the subscription to
btnSend, which retrieves the value from the message and posts the message to the worker.
The myWork.js file contains the following code.
self.onmessage = function (e) {
for (c in e.data) {
postMessage(e.data[c].toUpperCase());
}
}
This code subscribes to the onmessage event. In this example, when a message is received
from the creator, this code loops through each character, converts it to uppercase, and sends
the uppercased character back to the creator.
You can stop a web worker by calling the worker.terminate() method from the creator or
calling the close() method inside the worker itself.
Quick check
■■You want to perform an asynchronous operation in your browser code. Which
object can you use?
Quick check answer
■■Use the worker object.
Lesson summary
■■A web worker provides asynchronous code execution.
■■Communication to and from the web worker is accomplished by using the postMes-
sage method.