Inside this article, you’ll find information on all of the AJAX enhancements available in Internet Explorer 8 Beta 2.
In Internet Explorer 8 Beta 2, the maximum number of concurrent connections from a single host process connecting via broadband to a single server has been increased from 2 to 6.
These include tools to improve performance and client-side state management: local storage APIs, AJAX navigations, increased connections per host (plus a way to detect the number of connections on a host), and a scriptable connectivity event.
We’ve also worked on enhancing our communication objects and protocols. For example, safer and easier cross-domain communication is now possible through the XDomainRequest object and the W3C’s Access Control draft, as well as HTML 5.0’s cross-document messaging.
For up-to-the minute information on AJAX and other technologies in Internet Explorer, visit the Internet Explorer Developer Center at http://www.msdn.com/ie.
One of the great benefits of implementing AJAX-indeed, one of the main reasons for its existence-is the ability to update page content without navigating to a new page. With this convenience, though, come drawbacks that can confuse users. On an AJAX-heavy page, the Address bar is not updated with each update. Subsequently, the "travelog," or browsing history, isn’t updated either.
As an example, consider a mapping Web site such as Windows Live™ Search Maps or Google Maps. When using the AJAX-enabled features of those applications-such as pan and zoom-neither the Address bar nor the travelog is updated. Users who are used to the Address bar changing with each new page they navigate to or who rely on the browser’s Back and Forward buttons to navigate back and forth a page at a time may find this jarring. While some Web sites work around this limitation by navigating a hidden IFrame when updating content through AJAX, this technique can decrease performance.
To enable AJAX navigations, Internet Explorer 8 Beta 2 in IE8 mode (the default compatibility mode) treats updates to the window.location.hash property like individual, "traditional" navigations. When the hash property is updated, the previous document URL (which may be from the previous hash fragment) is updated in the Address bar and the travelog (and therefore the Back button). At the same time, a new hashChanged event is raised and the hash URL fragment is saved before navigating away from the page.
On AJAX-enabled pages that take advantage of this new functionality, when AJAX content changes, navigation is as seamless as usual, but the user can back up and go forward as if the AJAX navigation was a traditional navigation. The markup sample in Listing 1 demonstrates a use for this new functionality. In this case, the hash property is set when the onendzoom event of the Microsoft® Virtual Earth™ map control occurs. In other words, every time the user zooms in or out, the Address bar and travelog are both updated, enabling the user to navigate back and forth between zoom levels by using the Back and Forward buttons.
Every time the user zooms in or out, the fragment identifier in the Address bar is updated, as shown in Figure 1. On this page, that simply means the integer after the number sign (#) is incremented.
To store data on local machines, Web sites today often use the document.cookie property. However, cookies are limited in their capabilities; sites can only store fifty key/value pairs per domain, and the cookie programming model requires parsing the entire cookie string for data. DOM Storage objects-specified in the W3C’s HTML 5 Working Draft and implemented in Internet Explorer 8 Beta 2-provide a much simpler and more flexible global and session storage model for structured data on the client side.
Consider this scenario: A user is trying to find the best pair of tickets for a popular concert on an online ticketing site. For that purpose, the user opens several windows to make multiple requests, just to see the best seats she can get. If the site’s application is using cookies to store its session state, information could "leak" from one transaction into the other, potentially causing the user to purchase seats that she didn’t want without noticing. The potential for this sort of information "leak" becomes even more widespread as applications become more capable of offline behaviors, such as storing values locally for later return to the server, and as people start using more tabs to connect to the same Web site in parallel.
DOM Storage offers essential differences from cookies. For one, it offers significantly more available disk space than cookies. In Internet Explorer, cookies can store 4 kilobytes (KB) of data, whereas DOM Storage provides about 10 megabytes (MB) for each storage area. Furthermore, DOM Storage doesn’t transmit values to the server with every request as cookies do, and data in a global store never expires. Unlike cookies, it’s easy to access individual pieces of data using an interface that is supported in Internet Explorer 8 Beta 2 and other browsers, and sites can choose to store data for the life of a tab or until the site or the user clears the data.
// Store a key-value pair. localStorage.setItem("Sean","Purcell"); // Retrieve value string for a given key. var storeditem = localStorage.getItem("Sean"); // Remove item from store. localStorage.removeItem("Sean"); // Clear the store. localStorage.clear();
Now let’s see DOM Storage in action. Listing 2 is a code sample that will present you with a page (shown in Figure 2) with a text box and two buttons. Type something in the text box and then click Send to Store. This serializes the string to the DOM store. Now, close the browser tab or window, open a new one, and navigate to the same page again. In Internet Explorer 8 Beta 2, what you typed into the text box and committed to the store will still be there.
To see what happens without the DOM store, remove the body onload event to observe the past behavior.
On AJAX-enabled pages that take advantage of new AJAX navigations functionality, when AJAX content changes, the user can back up and go forward as if the AJAX navigation was a traditional navigation.
It’s important to note that DOM Storage is just a mechanism for Web applications to simply store data, and that there is no database behind it. For example, you can’t perform complex queries like search by value on the DOM store.
Internet Explorer 8 Beta 2 introduces several connectivity enhancements, including more accurate connectivity status information and an increase in the default number of concurrent connections to a single server.
Connectivity Status Indication
With Internet Explorer 8 Beta 2, your AJAX application can now fine-tune the user experience in the event the user’s connection is lost. Where before, there was no way for script running in Internet Explorer to determine the host’s connectivity status, Internet Explorer 8 Beta 2 can determine when the user has lost the connection, enabling your AJAX application to act accordingly.
The onLine property of the window.navigator and window.clientInformation objects has been available since Internet Explorer 4. However, through Internet Explorer 7, the onLine property only indicated whether the system was in "global offline mode," which users initiated by choosing Work Offline from the File menu. This was not useful in determining whether the user truly had an active connection. In Internet Explorer 8 Beta 2, however, the onLine property indicates whether the system is actually connected to the network.
Internet Explorer 8 Beta 2 also introduces new simple events. When the window.navigator.onLine property changes after a page is loaded, a simple event is raised on the page’s body element as follows.
- If onLine changes from true to false, the offline simple event is raised on the body element.
- If onLine changes from false to true, the online simple event is raised on the body element.
Finally, Internet Explorer 8 Beta 2 introduces new callback handlers to indicate a change in the status of a connection. The onoffline handler is raised when the user’s computer loses its network connection-for example, when the network cable is unplugged or the network adapter is disabled. The ononline handler is raised when the computer’s network connection is restored. Of course, these handlers are also raised when the user toggles the Work Offline setting on or off.
Let’s see these new connectivity status enhancements at work. Listing 3 is a sample that creates a page (shown in Figure 4) displaying the current connectivity status. It will automatically update as your network connection is enabled and disabled.
More Connections per Server
If you’re an Internet Explorer and AJAX expert, you may already know that with versions of Internet Explorer prior to Internet Explorer 8, you were limited to two concurrent connections to a single HTTP 1.1 server. Things were a bit better with HTTP 1.0 servers, as the limit was 4, but HTTP 1.1 connections are far more common today.
This two-connection limit was due to a mandate in the Internet Engineering Task Force’s RFC 2616. In 1999, when the spec was drafted, this limit was appropriate, considering the dominance of dial-up Internet connections, the uncommonness of script-heavy Web applications, and the relative scarcity of broadband connections. Today, however, broadband is much more commonplace. The need for more per-host connections is especially strong considering the increase in popularity of AJAX applications and pages, many of which send large amounts of data asynchronously. That and other improvements to general Web infrastructure have led to an increase in the maximum number of concurrent connections in Internet Explorer 8.
In Internet Explorer 8 Beta 2, the maximum number of concurrent connections from a single host process connecting via broadband to a single server has been increased to 6. It’s important to note, however, that the maximum number of concurrent connections over dial-up (with a modem over a telephone line) to a single server remains the same as for Internet Explorer 7 and earlier.
If you’ve implemented workarounds to circumvent the previous connection limitations, you may have compatibility concerns with this new behavior. In that case, and to avoid overwhelming your Web server, you may want to tailor content delivery based on the number of connections each client computer is capable of having open concurrently. For that reason, Internet Explorer 8 Beta 2 includes two new read-only properties of the window object that enable your server to determine the number of available connections on the client computer. Table 1 lists the new properties and their return values.
Depending on the value the property returns, you can choose to parallelize downloads or to change the priority of content delivery.
The sample in Listing 3 shows you these new properties in action. In Internet Explorer 8 Beta 2, this page will display the number of maximum connections available to your computer. If you are connected via broadband to the Internet, it will display "6" for each value. If you are connected via dial-up, the values will be "2" for HTTP 1.1 servers and "4" for HTTP 1.0 servers.
The XMLHttpRequest object was invented nearly a decade ago, primarily to enable Microsoft Outlook® Web Access to display e-mails without requiring a page refresh. Since its creation, however, its adoption has scaled up beyond the scope of its original design, while its functional design has not changed. Your advanced AJAX application may need finer control over AJAX requests than has typically been available.
XMLHttpRequest has been updated to add timeouts. This means that if your page periodically uses XMLHttpRequest to poll a server for response text and there is a delay, you can specify the length of time in milliseconds for the host to wait for a response before timing out the connection. Consider the potential reduction in user frustration for lack of feedback; where before, your page might have appeared "hung" indefinitely, it can now gracefully time out and inform the user of the timeout.
In addition, as you just read in the previous section, even though Internet Explorer 8 raises the maximum number of per-host connections to a server in broadband scenarios from two to six, dial-up scenarios are still limited to two. This means that, without a timeout set, Internet Explorer cannot open any new connections beyond the two-connection limit in dial-up scenarios. Timeout support enables you to preset a period of time after which the request will abort and make a new connection available.
// Create a new XMLHttpRequest object. xhr = new XMLHttpRequest(); // Set the XMLHttpRequest timeout value to 5 // seconds. xhr.timeout = 5000; // Event handler for XMLHttpRequest timeout. xhr.ontimeout=timeoutFired;
Now check out the new XMLHttpRequest capabilities for yourself. The code sample in Listing 5 cycles through the values of the XMLHttpRequest readyState property (the property that represents the state of the request) to demonstrate a timeout.
Open the page in Internet Explorer 8 Beta 2 and click through the dialog boxes. These are alerts that cycle through the readystate property values:
- 1: LOADING. The object has been created, but the send method has not been called.
- 2: LOADED. The send method has been called. Headers are available.
- 3: INTERACTIVE. Some data has been received.
- 4: COMPLETED. All the data has been received.
Since the timeout is set to 0.02 seconds, you will quickly see a "timed out" alert. If you want to cycle through more alerts, increase the timeout value.
Cross-domain Request ("XDR")
Web browsers have a security policy called the same site origin policy, which blocks Web pages from accessing data from another domain. Web sites often work around this policy by having their server request content from another site’s server in the backend, thus circumventing the check within the browser. Figure 4 illustrates this process for a typical mashup site.
In Internet Explorer 8 Beta 2, Web pages can simply make a cross-domain data request within the browser using the new XDomainRequest object, and without server-to-server requests. Figure 5 illustrates a cross-domain request (XDR). XDRs require mutual consent between the Web page and the server. You can initiate a cross-domain request in your Web page by creating an xdomainrequest object off the window object and opening a connection to a particular domain. The browser will request data from the domain’s server by sending an Origin header with the value of the origin. It will only complete the connection if the server responds with an Access-Control-Allow-Origin: * header. This behavior is part of the W3C’s Web Application Working Group’s draft framework on client-side cross-domain communication that the XDomainRequest object integrates with.
It’s important to note that to protect user data, cross-domain requests are anonymous, which means that servers cannot easily find out who is requesting data. As a result, you only want to request and respond with cross-domain data that is not sensitive or personally identifiable.
Compared to cookies, HTML 5 DOM Storage objects provide a much simpler and more flexible global and session storage model for structured data on the client side.
// Creates a new XDR object. xdr = new XDomainRequest(); // Indicates there is an error and the request // cannot be completed. xdr.onerror = alert_error; // The request has reached its timeout. xdr.ontimeout = alert_timeout; // The object has started returning data. xdr.onprogress = alert_progress; // The object is complete. xdr.onload = alert_loaded;
This snippet introduces the XDomainRequest properties and methods.
// Sets the timeout interval. xdr.timeout = timeout; // Gets the content-type header in the request. var content_type = xdr.contentType; // Gets the body of the response. var response = xdr.responseText; // Creates a connection with a domain's server. xdr.open("get", url); // Transmits a data string to the server. xdr.send(); // Terminates a pending send. xdr.abort();
As mentioned previously, XDR has two components: a client side that makes a request for data to a URL across domains, and a server side that responds with the Access-Control-Allow-Origin: * header and the data, which Internet Explorer then makes available to the requesting domain after performing security checks.
The code sample in Listing 6 demonstrates the client-side component of XDR. The sample refers to a fictional server, so you should feel free to use your local machine or a sandbox server to try this out.
On the server side, the browser will request data from it by sending an Access-Control-Allow-Origin: * header. It will only complete the connection if the server responds with an Access-Control-Allow-Origin with a value of *.
Cross-document Messaging ("XDM")
As you discovered in the section of this article on XDR, the browser’s same site origin policy blocks Web pages from getting data from other domains. This means that a richer experience is prevented since different domains on a single Web page can’t communicate with each other. Web sites work around this policy by creating nested IFrames and retrieving data transmitted through URLs. Another way Web sites work around this policy is by directly hosting script and other resource files from other domains. This second workaround only allows one-way communication. It is also a security risk because embedded script and resources run with the same privileges as the host Web site and have access to the user’s data like that stored in cookies.
// Posts the message data (text_sent) to the // target URI ("http://www.fourthcoffee.com"). target iframe.contentWindow.postMessage(text_sent, "http://www.fourthcoffee.com"); // Runs myFunction once a message is received. window.attachEvent("onmessage", myFunction);
Take a look at XDM in action to better understand how it works. Listing 7 is a page that sends a message to an IFrame (Listing 8) within the page. In our example, the page in Listing 7 resides on the domain contoso.com and the IFrame in Listing 8 resides on the domain fourthcoffee.com.
XMLHttpRequest timeout support enables you to preset a period of time after which the request will abort and make a new connection available.
You can try this out on your own locally. Just replace both http://www.fourthcoffee.com and http://www.contoso.com with http://localhost (of course, you’ll need to enable IIS (Internet Information Services) first) and place both files in the inetpub folder on your hard drive. What you’ll see looks a lot like Figure 6.
We hope you’ve enjoyed learning about the ways you can develop AJAX applications in a way that’s better and smarter than ever before. If you haven’t downloaded Internet Explorer 8 Beta 2 yet, now’s a great time to do so, and try out the new functionality!