AJAX - The Complete Reference

(avery) #1

260 Part II: Developing an Ajax Library^


}; /* end callback function */

if(window.attachEvent)
window.attachEvent("onunload", sendConnectionStats);
else
window.addEventListener("unload", sendConnectionStats, false);
}

To see this in action, run the example at http://ajaxref.com/ch6/monitorconnectionstats.
html, open the link to the results in a new window, and then leave the primary window.
Refresh the results page and you should see the network statistics collected for your session
as demonstrated in Figure 6-17.

NNOT EOTE If you looked closely at the code presented, you’ll notice a new options flag, oneway. This
indicates that the request is one way and thus not looking for a callback. Given that this request
is made upon unload, it will throw an error if thought to be bi-directional. You’ll see many more
of these special case additions to address application architecture concerns in Chapter 9.

In the case of the client-side monitoring conditions, what should happen if the situation
starts to fail consistently? The client could wait until unload to send the data, but maybe some
indication of trouble should be sent as soon as possible. Unfortunately, if communications are
failing, such as large numbers of timeouts, sending another request to the server that is timing
out is kind of foolish. One solution would be to issue a request to another domain but of
course this is not possible using an XHR given its same origin policy restriction. Instead, it
would be necessary to use an image or <script> technique as discussed in Chapter 2 to
transmit the situation to a logging server some other place on the Internet. If that does not
transmit either, it is a safe assumption that the user has significant network problems and
the best action might be to save the data to a cookie for later retrieval.
There are many decisions that could be made architecturally once it is clear that
problems are occurring. Increasing the tolerances for timeouts could help in the case of a

FIGURE 6-17 Move beyond blissful ignorance, record network errors
Free download pdf