Creating a Waiting Screen


document.getElementById("loading").style.visibility = "hidden"; 

One of the largest obstacles for modern web applications is latency: Something happens, but in the background. You do have to inform the users; otherwise, they will not notice that something is coming up. One way of doing this is by changing the mouse cursor (see Chapter 4, "CSS"); another way is by using a waiting banner. Many applications let a banner labeled with "waiting" or "loading" fade in when an XMLHttpRequest call is executed; one of the first websites to use this was Google Mail.

Actually, this phrase requires more DHTML than AJAX. When the (asynchronous!) call is sent to the server, the loading screen is shown and positioned in the upper-right corner (you can, of course, use any arbitrary position of your liking). After data comes back from the server, the banner is made invisible again. The following code implements this in a browser-agnostic fashion:

Implementing a Waiting Screen (waiting.html)

[View full width]

<script language="JavaScript"   type="text/javascript" src="/books/3/490/1/html/2/xmlhttp.js"></script> <script language="JavaScript"   type="text/javascript"> var XMLHttp = getXMLHttp(); window.onload = function() {   XMLHttp.open("GET", "delay.php?" + Math.random());   XMLHttp.onreadystatechange = handlerFunction;   XMLHttp.send(null);   with (document.getElementById("loading")) {     style.visibility = "visible";     if (navigator.appName ==       "Microsoft Internet Explorer") {       style.posLeft =         document.body.clientWidth - 75;       style.posTop = 0;     } else {       style.left = (window.innerWidth - 75) + "px";       style.top = "0px";     }   } } function handlerFunction() {   if (XMLHttp.readyState == 4) {     document.getElementById("loading").style.visibility = "hidden";     window.alert("Returned data: " +                  XMLHttp.responseText);   } } </script> <span  style="position: absolute; visibility: hidden; background-color: red;  width: 75px;">Loading ...</span> 

Figure 11.3 shows the browser while waiting for results: The banner appears (and vanishes again after the data from the HTTP request has arrived).

Figure 11.3. The waiting screen.


Warning

The XMLHttpRequest object will not notice you if anything with your HTTP request goes wrong, which also includes timeouts. So you should use the pattern shown in the phrase "Aborting an HTTP Request" to check the status of the request after a certain period. If the request has not been completed until then, you should restart itor print out an error message, and let the waiting banner disappear.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net