HTML and CSS Reference
In-Depth Information
Browsers are effectively single-threaded applications, in that
when JavaScript is running or perhaps being parsed, the page
isn't rendering. Equally, when JavaScript is performing a long
and complicated function, the whole browser can be seen to
lock up. What a Web Worker does is introduce a simplified idea
of threads for browsers. A worker allows me to ring-fence a par-
ticular block of code and it will run without affecting the browser
at all in a new, concurrent thread of operation, allowing the main
browser thread to continue uninterrupted.
NoTE The new
XMLHttpRequest Level 2
object ( http://www.w3.org/TR/
XMLHttpRequest2/ ), out of
scope for this topic but already
in WebKit and Firefox, supports
cross-domain requests (with the
right level of server security).
It also includes progress events
for monitoring uploads.
Chit chat with the Messaging API
I wanted to show you the Messaging API first because the
Web Worker, WebSocket, and Server-Sent Event APIs (the latter
two discussed in the next chapter) all use this common method
of communication. So think of this as your gentle primer on
communication.
The Messaging API has very good support across all brows-
ers—yes, including Internet Explorer (IE)—and offers a simple API
for posting plain text messages from one origin (or domain, to
you and me) to another. For example, if you want to send some
information to a window you have in an iframe, you can do it
using the Messaging API. This will still work if the window is on a
completely different domain than the site hosting the iframe.
Sending messages across domains
If Bruce has a document that wants to communicate with
my document—say either in an iframe or perhaps in a pop-up
window—it needs a reference to the window object (of my docu-
ment) and he can then call the postMessage method to pass
some message to it. The JavaScript in Bruce's document will
look like this:
var t = document.getElementsByTagName('iframe')[0];
t.contentWindow.postMessage('favourite instrument?',
¬ 'http://brucelawson.co.uk');
The target origin being passed to postMessage in the second
argument is required, and it must match the origin of your
contentWindow object (the target window, my document in this
example). If the origins don't match, a security error will be
thrown, stopping the script from continuing. If the origin isn't
 
 
Search WWH ::




Custom Search