HTML5 Guidelines for Web Developers

(coco) #1

250 Chapter 10—Web Workers


object, and the document object. What at first seems like a great limitation is in
fact very sensible on closer inspection. If scripts running in parallel access the
same resources and change them, very complex situations can arise as a result.
The strict isolation of the workers and their communication via messages makes
the JavaScript code more secure.
The start of a new worker is relatively labor intensive for the operating system,
and each worker takes up more memory space than executing the same func-
tions without workers. The advantages are obvious nevertheless: The browser
remains able to react, and complicated calculations can be carried out in paral-
lel, leading to a potential increase in speed for modern hardware.
When created, each worker receives the script containing the code for the worker:

var w = new Worker("calc.js");

The script, in this case calc.js, contains JavaScript code that is executed when
the worker is called. Optionally, the worker contains an event handler for the
message event, reacting to requests by the calling script. In practice, this supplies
the worker with data for calculations and triggers the computing process:

addEventListener('message', function(evt) {
// evt.data contains the data passed

The data transfer from the calling script to the worker and vice versa takes place
via the postMessage() function. To supply the worker w with data, the following
call is suitable:

w.postMessage(imgData);

JavaScript objects can be passed to the postMessage() call and converted to JSON
strings internally by the browser. The important point is that this data is copied
with every call, which can mean a considerable loss of speed in the case of large
amounts of data.
As mentioned earlier, workers have no access to the window object. Exceptions are
the functions of the WindowTimers interface: setTimeout()/clearTimeout() and
setInterval()/clearInterval() can also be used within a worker. And workers
can load external scripts, which is why the importScripts() function was intro-
duced. One or more JavaScript files can be passed to this function (separated by
commas), which the worker loads and can then use.
The worker also has read access to the location object, where the href attribute
returns an absolute URL to the running worker. Via the XMLHttpRequest, work-
ers can communicate with web services.
Free download pdf