Wednesday, January 7th, 2009
Web Workers update for Firefox 3.1
<p>Ben Turner has nicely written up the state of Web Workers that we will see in Firefox 3.1 (in beta 2 right now).To show the latest, Ben got a demo working that decrypts Weave data in the client using a Worker:
- // Launch the main worker.
- if (!worker) {
- worker = new Worker("weaveDecryptorWorker.js");
- worker.onerror = onerror;
- worker.onmessage = onmessage;
- }
- worker.postMessage({ types: types,
- user: document.getElementById("username").value,
- phrase: document.getElementById("passphrase").value,
- server: document.getElementById("server").value });
What’s changed?
- The
navigatorobject has been added to the worker scope. It contains the following strings that identify the browser, just as from normal script:appNameappVersionplatformuserAgent
- Workers can now be forcefully killed via the
terminatefunction. Calling this function on a worker will immediately stop the worker’s execution. - Workers may only be created from a worker script that is hosted within the same origin as the parent page.
- URIs for subworker scripts and imported scripts are now resolved relative to the parent worker script location instead of the owning page.
- Error handling has been reworked according to recent spec changes. A worker script can now define an
onerrorhandler that will be called with an error event with details about the exception. If the handler callspreventDefaulton the event object then nothing else happens. IfpreventDefaultis not called then the error event propagates to the parent scope’s (either a worker or the parent page)onerrorhandler. - Numbers, booleans, and even objects may be passed to
postMessagein addition to strings. The only restriction is that objects may not contain functions or cyclical references (since we use JSON under the hood). This simplifies previous code that needed to use the JSON object to manually encode/decode the strings passed topostMessage.
Related Content:











Too bad there can’t be functions in the objects sended in messages between workers (other than strings to eviluate)
But anyway: nice! Can’t wait to start using workers ;-)
Having the ability to pass functions will mean that you will be able to pass closures that carry the surrounding variables (scope), meaning state and therefore making it extremely hard to have asynchronous workers.
As far as I see workers are some implementation/interpretation of actor-based concurrency, right?
@Vladev: it wouldn’t be “extremely hard”, it would just mean having to provide mutex objects, context synchronization, locking, etc… more like robust async programming in an advanced server language like C#, which is not extremely hard.
At any rate, this is a wonderful first step towards native support for threaded javascript. Of course, tis already available with plugins like Gears, but native support is sorely needed.
Keep it up.