HTML and CSS Reference
In-Depth Information
passed to and from the worker by messages. Set up a listener for mes-
sages from the worker that logs the data using the usual function:
worker.onmessage = function(event) {
log(event.data);
}
Similarly, you signal that the worker is to start computing by passing it
a message using postMessage :
<button onclick="worker.postMessage('Starting'); return false;">
Start worker
</button>
In the function, all attempts to access the DOM must be removed. This
means replacing the log function with calls to postMessage() :
function kill_browser() {
var j = 0;
var n = 1e9;
var p = n/10;
for (var i=0;i<n;i++) {
if (j++ > p) { j=0; postMessage(i); }
}
postMessage('Done');
}
Finally, the worker needs to listen to messages so it knows when to
start:
onmessage = function(event) {
postMessage(event.data);
kill_browser();
}
You can try this example for yourself with the files ch05/web-workers-
1.html and ch05/web-worker-1.js.
Workers are a powerful addition to the web author's toolkit, allowing
you to write more desktop—like applications without resorting to
advanced JavaScript trickery. In the next section, we'll summarize
browser support for everything covered in this chapter.
Search WWH ::




Custom Search