Web Workers is a specification for running client side scripts on the browsers in the background in parallel to the web page, so if you need to do heavy calculations you could split the work across multiple workers.
This is a new work-in-progress feature, so not all browsers can execute it.
Here is what it looks like. Your HTML file will consist of this in the script (internal or external):
var worker = new Worker('worker.js');
worker.onmessage = function(event) {
document.getElementById(elemID).textContent = event.data;
};The Worker object will calls the Worker contructor, and return a Worker object.
The worker.js file will be like this; I’ll use the example from Section 1.2.1:
var n = 1;
search: while (true) {
n += 1;
for (var i = 2; i <= Math.sqrt(n); i += 1)
if (n % i == 0)
continue search;
// found a prime!
postMessage(n);
}So by calling the worker.js file from within our page we could have the Worker go crazy with finding those prime numbers, while leaving the user interface smoothly running.
One thing to note before I go on is that the Worker object doesn’t manipulate the elements on a page, it only interfaces with the page through the onmessage, and postMessage functions, and other messages sent across the MessagePort.
The postMessage function — defined in Section 4.1.2 — is used to send messages back to the web page and triggers an onmessage event. There is actually a lot more to postMessage.
message event — also defined in Section 4.1.2 — is the event fired once the Worker sends a message back to the page.
Seems a lot like Ajax, no? :)
There is quite some more to cover on this topic, and I’m falling asleep typing this. You can read up more:
- whatwg - Web Workers
- Web Reflection: A JavaScript WorkerLocation
- John Resig - postMessage API
- John Resig - Computing with JavaScript Web Workers
Don’t hesitate to correct my mistakes :)

0 comments:
Post a Comment