HTML and CSS Reference
In-Depth Information
running piece of code tie up the UI indefinitely, but it is still far less efficient than if
Web Workers can be used.
By creating a Web Worker, you are creating a bridge between the main JavaScript in
your page and a sandboxed piece of JavaScript running in another thread. The two
sides of the bridge communicate with each other by asynchronously sending and re-
ceiving messages, using postMessage(...) and listening for the message event.
An asynchronous Ajax call using XMLHttpRequest (“XHR”) to a server is
quite similar to sending and receiving asynchronous messages to/from
a Web Worker.
The Web Workers communication interface also allows errors to be sent and received.
To signal an error from inside a worker, simply throw a JavaScript error, like so:
self.onmessage = function(evt) {
var data = [];
for (var i=0; i<1500; i++) {
data[i] = [];
for (var j=0; j<1500; j++) {
data[i][j] = Math.random();
if (data[i][j] == 0) {
throw "I don't like zeros in my array!";
}
}
}
self.postMessage(data);
data = null; // unassign our copy of the data now, to free up memory
};
To receive an error message from a worker, listen for the error event:
var worker = new Worker("init_array.js");
worker.onerror = function(err) {
alert("An error occurred in the initialization of the array.");
throw err; // optional
};
worker.onmessage = function(evt) {
alert("Data array initialization finished!");
var data = evt.data;
};
worker.postMessage();
A Web Worker is sandboxed away from the main page, and basically can only com-
municate with the page using these messages. That means the worker cannot access
the DOM to read or modify any information. Also, UI-centric tasks like calling an
alert(...) dialog are not allowed.
 
Search WWH ::




Custom Search