HTML and CSS Reference
In-Depth Information
Now that we know we've got support (Safari, Chrome, Opera,
and Firefox currently support Web Workers) we can go about
creating a new worker:
var worker = new Worker('my_worker.js');
A new worker object is flred up, reads in the my_worker.js
JavaScript flle and is now happily running and ready to be used.
At this point, you'd be forgiven for thinking that you can call meth-
ods inside the worker from your document, and in fact that data
can be returned from the worker to your document. Poppycock!
No, in fact to work with a worker, everything must be communi-
cated through posting messages between the worker and your
document. Like some scene from omeo and Juliet, exchanging
letters of love between the browser and the worker.
The only way you get can information to the worker is via
postMessage :
worker.postMessage('hello worker!');
The only way you can receive information from the worker is via
the onmessage event handler:
worker.onmessage = function (event) {
alert('The worker just sent me this: ' + event.data);
};
Yo u s h o u l d n o w b e r e c o g n i s i n g t h e postMessage/onmessage
combination from the Messaging API from earlier in this chapter.
Yo u r e m e m b e r h o w w e c a in o in l y s e in d a in d r e c e i v e s t r i in g s i in t h e
Message API? You won't be surprised to know, then, that the
Web Workers have the same constraint.
Equally, the code inside the worker must also communicate
using the postMessage / onmessage combo. However a Web Worker
doesn't have the same access as your normal document: It's very
much sandboxed in and has access to only a select few APIs and
functions, as I'll show you in the next section.
The only other method available to you via the worker object
is terminate, which does exactly what it says on the tin. The
worker ceases to run and worker object becomes limp and use-
less. In particular, you can't resume the worker; you'd have to
create a brand new one.
note A slight caveat: Web
Workers are supposed to be
able to send objects, just as the
Messaging API is, but most
browsers coerce the object to a
string. However, Firefox has
implemented internal JSON.
stringify / JSON.parse
behind the scenes of sending and
receiving messages to and from
workers so you don't have to. So
there's hope if the other browsers
follow suit and allow us to send
object through the messaging
system.
 
Search WWH ::




Custom Search