Web Workers6 are not part of the HTML5 specification, but you may find them useful if you need to do some background processing on the client side, so they’re worth mentioning.
We use JavaScript for all of our client-side coding, but JavaScript is a single-threaded language—only one thing can happen at a time. If a task takes a long time, we force the user to wait until the task has finished. Web Workers solve this problem by creating a simple way to write concurrent programs.
If we have a script called worker.js that does some image processing, we can invoke it like this:
var worker = new WorkerC”wor/cer. j s ” ) ;
Any JavaScript file can be launched as a worker, but in order for the worker to be independent, your worker script can’t access the DOM. That means you can’t manipulate elements directly.
Our main script can send messages to the worker script using postMessage() like this:
$(“#button”).cli ckCfunction( e v e n t ){
$ C ” # o u t p u t ” ) . h t m l ( “starting…”);
w o r k e r . p o s t M e s s a g e ( ” s t a r t ” ) ;
} ) ;
Our worker script can then send messages back to the main page, also using the postmessage() method.
onmessage = function(event) {
i f C e v e n t . d a t a === ” s t a r t ” ) {
/ / t h i s loop counts. Do something awesome i n s t e a d ,
for (var x = 1; x <= 100000; x++){
postMessage(x);
}
We respond to those events by listening to the onmessage event in our main script. Every time the worker posts back, this code will fire:
worker.onmessage = function( e v e n t ) {
$(“#output”).html(event.data);
}
This API works just like the API for cross-domain messaging, which we talked about in Talking Across Domains, on page 200. There’s no support for Web Workers in Internet Explorer, so you’d need to rely on Google Chrome Frame, but if you’re looking to do some heavier nonblocking client-side work, you’ll want to look into this further.