AJAX - The Complete Reference

(avery) #1

Chapter 3: XMLHttpRequest Object 89


PART I


these are relatively harmless, save one in Internet Explorer that will break the object’s
functionality. To demonstrate this, first use a global XHR and set the onreadystatechange
in the wrong place, in this case before the open() method. The readyState for the XHR
object will not work properly on the second and subsequent uses, as demonstrated here:

Run: 1

Run: 2

Interestingly, the various quirks of the readyState value are rarely felt in practice since
most folks are looking solely for the final 4 value. However, you’ll see later in the chapter
that it is actually possible in some browsers and situations to look at data as it is loaded as
opposed to waiting for the final readyState value to be reached.

readyState Needs Time to Change
One particularly important aspect of asynchronous communication related to the
onreadystatechange functionality is the simple fact that in browser-based JavaScript,
callback functions cannot be invoked until the script interpreter has a free moment to do
so. There is no suspend and resume aspect to JavaScript execution in the typical single-
threaded style that is implemented in Web browsers. If you make a request and then enter
into heavy calculations or other blocking activity, control will not be handed back long
enough for the interpreter to invoke the readyState value change and the callback
function will not be invoked. You can prove this to yourself by trying to run the example at
http://ajaxref.com/ch3/longprocess.html, but given the difficulty in forcing the issue you
might rather watch a movie that shows this situation in action at http://ajaxref.com/ch3/
longprocessmovie.html.
Free download pdf