Demo - Firefox 3.5: Web Workers in action
By Paul Rouget on Wednesday 15 April 2009, 15:00 - shared - Permalink

One of the new cool features of Firefox 3.5 is the support of Web Workers (see the WhatWG specification).
Web Workers give you a way to execute a part of your Javascript in a thread. That means smoother pages.
I've written a little demo showing Web Workers in action.
But first, a little explanation of the code: I've developed the Simulated Annealing algorithm, which is useful for finding the shortest path between several points (displayed on a <canvas/>).
Here is a demo (without Web Workers). Click on the load button, then on the start button.
The main demo
So, the main demo (with Web Workers) uses this algorithm to find the shortest path of 6 sets of points. The algorithm could be executed in a Worker, or not.
- Try it
- if you don't have Firefox 3.1/3.5, see the screencast
See the difference! A bit faster and way smoother (it doesn't freeze your web page, the page is still alive during the process). Notice the Animated PNG: it gets stuck during the process if you don't use Workers.
Just one rule for Workers: you can't play with the DOM inside a Worker, but you can delegate DOM modifications to the main thread (see postmessage/onmessage methods).
Why you should use Web Workers
Since you can now do some amazing things with HTML5 (canvas, video, ...), you may need to write some heavy algorithm. It could be easier to execute every non-DOM related code in a thread. It will make your code faster, but above all, it will make your web application smoother, and the code cleaner (to avoid Spaghetti code)! Note that you can also use a XMLHttpRequest in a Worker.
Be creative ;)
Comments
is this under GPL or we have to pay to get this
thanks
Greate work!
@LinkBuilder:
Free: http://creativecommons.org/licenses...
Just wondering: Are these worker threads executed in a different native thread as well? This would help to get the dual core processors used by web applications as well.
@Sebastion: yes
Short note: The basic features of this smart Demo working also under Firefox 2.0.0.20
can i get the code of this demo ?i am learning web worker.
so i want to know how it works
thanks a lot
@halo dude, the web is open, just do a ctrl-u
Hi, great example. I've been going through your code until I got stuck at this line in "annealing.js"
function ThreadedAnnealing() {
this.worker = new Worker("Worker.js");
};
Where is "Worker.js"?
@Marko : Worker.js is loaded from the server in the same way as images or scripts.
The path is relative to the page if it is loaded from a page, or relative to the worker if it is a subworker.
Does anyone have a working example of an XMLHTTPRequest working in a WebWorker? I always get this error even if using relative urls.
Component returned failure code: 0x805e000a [nsIXMLHttpRequest.open]
This is the error for an incorrect domain from what I can work out, but everything is calling the same domain. I am posting data.