Hacking Gmail

(Grace) #1

Chapter 5 — How Gmail Works 55


FIGURE5-2: The main interface divs


Introducing XMLHttpRequest


I like to think of this as quite a romantic story. JavaScript, you see, has had a bad
rap over the years: it’s commonly misconceived as a scrappy language for dodgy


website effects circa 1999, and up there with the tag as something to be
avoided by the truly righteous web developer. This is, of course, utter rot: Modern


JavaScript is a rich and powerful language, and is rapidly regaining momentum.
Perhaps since IE5 was launched, and certainly since Mozilla and Safari became


mainstream, the majority of browsers have been capable of doing some very clever
things in JavaScript. It’s just that no one bothered to look.


One such function is XMLHttpRequest. Invented by Microsoft and now univer-
sally implemented, it allows a JavaScript program to communicate with a server in


the background, without refreshing the page. This is very key for Gmail. It means
that the JavaScript code can, upon a button push or any other trigger, send a tiny


request to the Gmail server, parse the response, and throw it onto the screen,
entirely without refreshing the page or causing any more traffic than is really nec-


essary. It’s blazingly fast, especially if you have a server optimized for just such a
thing. Google, naturally, does.


Using XMLHttpRequest Yourself


To get an idea of just what is going on, it’s a good idea to use XMLHttpRequest
yourself. In this section you’ll use it to create a little application of your own. You


can skip this section if you’re not interested in a deep understanding, but it’s pretty
cool stuff to play with anyway.

Free download pdf