Chapter 2. Interoperability and Compatibility

Web development is hard. An increasingly broad set of major browsers coupled with millions of configurations and over a billion Internet users has redefined the web development process as a whole. Web developers and browser vendors have attempted to rein in the chaos with modernized web standards such as HTML 4.01, HTML 5, CSS 2.1, and CSS 3. IE 8 includes better support for widely adopted web standards than its prior versions, in many (but not all) cases allowing developers to write one page that works in multiple browsers. In this chapter, I cover those standards and interoperability improvements in IE, detail compatibility features, and ways to handle the oftentimes competing forces between standards and compatibility.

Standards Support and Interoperability

The "standards by default" philosophy expressed by the IE development team throughout the IE 8 release cycle points toward a new product goal of wide-reaching standards support. Notably, IE 8 provides full support for the CSS 2.1 specification and introduces support for new features specified in stable areas of the HTML 5 specification. This section highlights the improvements in IE 8 since the IE 7 time frame, and provides a supportability baseline for developers looking to create interoperable web applications.

HTML 4.01, HTML 5, and DOM Spec Support Improvements

IE 8 introduces a number of improvements in its support of the HTML 4.01 standard; it is the most used and recognized document markup language on the Web today. Using IE 7 as a base, IE 8 offers the following enhancements and fixes to its implementation of the HTML 4.01 specification:

  • <p> element closure: Paragraph elements (<p>) are automatically closed whenever one of the following tags precedes its closing tag or its closing tag is not present: <table>, <form>, <noframes>, and <noscript>.

  • <object> fallback: When IE fails to load a resource from an <object> tag, IE will "fall back" by displaying the content contained within that tag.

  • <object> as image: When IE encounters an <object> tag that refers to an image resource, it will render that image as if it were embedded in an <img> tag. In prior versions, IE would display an image resource through this tag, but would not offer proper resizing or borders, and would in some cases display scrollbars.

The HTML 5 and various DOM specs from the W3C offer web developers a rich set of tools and events to enhance web pages and increase productivity. IE 8 implements a few portions of these specs already implemented by other browsers:

  • Ajax hash navigation: Hash-based page navigations (where only the fragment component of the URL changes) are now stored as navigation events. This means users can use the back and forward buttons to "navigate" between states of an Ajax application. This includes support of the onhashchange DOM event.

  • DOM storage: Web applications can access a new storage object to persist data and settings on a user's machine. The window.sessionStorage and window.localStorage objects offer applications up to 10MB of local storage space for this data.

  • Cross-document messaging: This enhancement introduces a new communication structure for <iframe>-based documents within a browser window, even when the documents originate from different domains. These documents can now use the postMessage API to ensure that cross-document data transfers are mutually agreed upon, providing extra protection to users.

  • Online/offline events: The onoffline and ononline events can now be used to detect loss and restoration of network connectivity. Using popular Ajax techniques combined with DOM storage, applications can function even while offline.

  • CSS 2.1 and CSS 3 Support Improvements

IE 8 provides full support for the CSS 2.1 specification, a widely used standard for defining document styles and building rich web user interfaces. Table 2-1 describes the properties that have been changed or added since IE 7's CSS 2.1 support:

Table 2.1. CSS 2.1 Improvements from IE 7 to IE 8

CSS 2.1 Property Set

New and Fully Supported Properties for IE 8

@ rules

@page

Border and layout

border-collapse, border-spacing, border-style, caption-side, empty-cells

Color and background

background-position

Keywords

inherit

Font and text

font-weight, white-space, word-spacing

Functions

counter(), attr()

Generated content

content, counter-increment, counter-reset, quotes

Lists

list-style-type

Positioning

bottom, display, left, right, top, z-index

Printing

orphans, page-break-inside, widows

Pseudoclasses

:active, :focus, :lang(), @page :first, @page :left, @page :right

Pseudoelements

:after, :before

User interface

outline, outline-color, outline-style, outline-width

IE 8 also offers limited support for CSS 3 property sets. CSS 3 extends and enhances CSS 2.1 functionality and offers a richer set of controls over styling and display of documents across a wide range of devices. IE 8 implements the CSS 3 properties shown in Table 2-2.

Table 2.2. Available CSS 3 Features in IE 8

CSS 3 Property Set

Support Level

Properties

@ rules

Partial

@font-face

Attribute selectors

Full

Namespaced (ns|attr), Prefix [^=], Substring [*=], Suffix [$=]

Combinators

Full

General Sibling (~)

Font and text

Partial

ruby-align, ruby-overhang, ruby-position, text-align-last, text-justify, text-overflow, word-break, word-wrap, writing-mode

Positioning

Partial

overflow-x, overflow-y

User interface

Partial

box-sizing

Document Modes and Versioning

Not all web pages were designed for the latest web standards, and many implement IE-specific functionality that was broken by IE 8's migration toward interoperability. In this section I describe compatibility features that web applications can utilize to get downlevel IE functionality, allowing developers of those applications to migrate toward standards-based implementations in the time frame of their choosing.

Quirks Mode, Document Modes, and X-UA-Compatible

Markup interpretation changes between web browser versions has occurred since the creation of browsers and web standards themselves. In the aftermath of the first browser wars between IE 4 and Netscape 4, newer browsers were left to cope with a web landscape filled with differing interpretations of what markup and styles were (caused by the competing implementations of browsers in the late 1990s). Without a way to tell what a page was doing and why, further modernization of standards would have been stifled due to the fact that existing pages relied heavily on old behavior. The DOCTYPE header was created as a result, allowing web developers to "tell" browsers what standards and implementations pages were originally created for.

This was only a temporary fix. In the mid-2000s, three major events happened: the number of widely used web browsers significantly increased, developers started building more complex web applications, and the push for interoperability and standards among browser vendors strengthened. Newer browsers on the scene, such as Safari and Firefox, adhered more closely to newer standards because of their relatively young age; IE, on the other hand, was left behind supporting legacy and enterprise applications that relied on older standards. IE 8 was the browser's first major attempt at catching up to these newer standards, and just like in the 1990s, the problem of what to do with legacy pages arose.

IE 8 added document modes as a second set of directives that developers can use to tell IE how to handle legacy web pages. They can be specified through the X-UA-Compatible HTTP response header or corresponding <meta> tag. DOCTYPEs, by default, are not honored, but developers can opt into using this older versioning model.

Document Modes

Document modes are directives that tell IE what legacy compatibility measures, if any, should be applied. Given the functionality changes made in IE's page display and level of standards support since IE 6, many applications were written to target older releases rather than web standards. While standards mode rendering is "on by default" in IE 8 and higher, IE offers a number of modes that pages can opt into, allowing them to be parsed and displayed in a way that they were designed for.

IE 8 includes support for a number of document modes, including Quirks mode (behavior similar to IE 5). These modes aim to emulate targeted IE versions, and each has a different level of DOCTYPE support (see Table 2-3).

Table 2.3. Available Document Modes in IE 8

Document Mode

Emulates

Header Value

Definition

Quirks mode

IE 5.0

IE=5

Displays a page based on the DOCTYPE specified. This behavior emulates that of IE 5.0.

IE 7 Standards mode

IE 7.0

IE=7

Displays a page using IE 7's interpretation of web standards. DOCTYPE is ignored.

IE 8 Standards mode

IE 8.0

IE=8

Displays a page using IE 8's interpretation of web standards. DOCTYPE is ignored.

IE 7 Emulation mode

IE 7.0

IE=EmulateIE7

Displays a page as if it were run in IE 7 Standards mode, but honors any DOCTYPE specified.

IE 8 Emulation mode

IE 8.0

IE=EmulateIE8

Displays a page as if it were run in IE 8 Standards mode, but honors any DOCTYPE specified.

Edge mode

(Latest)

IE=edge

Always opts into the most current standards interpretation of an IE version (e.g., IE 9 Standards mode on IE 9).

The header value associated with each document mode is used by web pages to target a specific document mode. I discuss how to use these values in the following sections.

Targeting Quirks Mode and Document Modes in Markup

Web pages can opt into a specific mode by using the X-UA-Compatible <meta> tag within a page's <head> element. Listing 2-1 uses the <meta> tag to inform IE that a page should be loaded in IE 7 Emulation mode (IE=EmulateIE7).

Example 2.1. HTML <meta> Compatibility Header Example

<!--  Load page in IE7 Emulation Mode -->
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7">

Older pages that wish to use older interpretations of standards can use a DOCTYPE header and <meta> tag to inform IE of this decision. Listing 2-2 shows a page that uses the Loose HTML 4.0 specification and that wishes to be displayed in Quirks (IE 5) mode.

Example 2.2. DOCTYPE and Corresponding X-UA-Compatible <meta> Tag

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
   <head>
   <!--  Load page in IE5 (Quirks) Mode -->
   <meta http-equiv="X-UA-Compatible" content="IE=5">

Targeting Document Modes from the Server Side

Specifying a document mode using the X-UA-Compatible <meta> tag is straightforward, but it doesn't fit all scenarios. Large web sites and content management systems (CMSs) can have thousands of web pages, and some servers can host thousands of web sites. Adding the <meta> tag to every page might not make sense for these types of web sites and hosting constructs.

Developers that wish to apply an IE mode across a web server or web site can do so by adding a new HTTP header to any web server configuration. The header name is X-UA-Compatible, and its associated value represents the desired mode of pages hosted within that server configuration. Not only does this apply settings server-wide, it actually causes a bit of a performance gain over the META tag (since IE knows the mode before parsing the page rather than afterward).

Adding the X-UA-Compatible Header to IIS

Developers can add the X-UA-Compatible header to IIS through Internet Information Services (IIS) Manager (found in Control Panel

Adding the X-UA-Compatible Header to IIS
Adding the X-UA-Compatible header to an IIS server configuration

Figure 2.1. Adding the X-UA-Compatible header to an IIS server configuration

This change can be made through the IIS 7 configuration file as well. Developers can add the <add> tag in the <customHeaders> portion of a .config file in %System32%/inetsev/config (see Listing 2-3).

Example 2.3. Adding the X-UA-Compatible HTTP Header to IIS 7 Config XML

<?xml version="1.0" encoding="utf-8"?>
...
<configuration> ...a
   <system.webServer> ...
      <httpProtocol> ...
         <customHeaders> ...
            <add name="X-UA-Compatible" value="IE=EmulateIE7" />

Adding the X-UA-Compatible Header to Apache

Apache allows custom headers in its global context or within Configuration in its httpd.conf configuration file. As in IIS, the X-UA-Compatible header can be added to this configuration, allowing developers or server administrators to run a whole site or server in a certain IE mode. Before adding the header, an Apache configuration must load the mod_headers module. Once in place, the Header set command can be used to indicate the desired IE mode (see Listing 2-4).

Example 2.4. Adding a Global Header for X-UA-Compatible

Header set X-UA-Compatible "IE=EmulateIE7"

The previous example shows how to set X-UA-Compatible globally. Most complex Apache configurations are set to host multiple web sites using Apache's Configuration tags. Instead of applying a header globally, developers and administrators can place it within directives like <Directory>, <Files>, <Location>, and <VirtualHost> to limit the scope of a header's application (see Listing 2-5).

Example 2.5. Adding a Configuration-Based Header for X-UA-Compatible

<Directory /var/www/httpd/website>
   Header set X-UA-Compatible "IE=EmulateIE7"
</Directory>

Feature Controls for Document Modes

Web sites aren't the only applications that use IE. Compatibility is also important for desktop applications hosting the WebBrowser control.

Applications wishing to opt into a particular document mode can do so through the FEATURE_BROWSER_EMULATION feature control key for a specific process file name. It is found in the SOFTWAREMicrosoftInternet ExplorerMainFeatureControl key and can be placed in both the HKEY_LOCAL_MACHINE and HKEY_CURRENT_USER hives. This feature control forces any instance of the WebBrowser control loaded within that process space to run all pages in a particular document mode. The available modes for applications are listed in Table 2-4.

Table 2.4. Feature Control Keys for Compatibility Modes

Compatibility Mode

Feature Control Key

Value (DWORD)

IE 7 Standards mode + DOCTYPE

FEATURE_BROWSER_EMULATION

7000 (0x1B58)

IE 8 Standards mode + DOCTYPE

FEATURE_BROWSER_EMULATION

8000 (0x1F40)

IE 8 Standards mode

FEATURE_BROWSER_EMULATION

8888 (0x22B8)

IE 8 and IE 7 Standards modes are the same modes used within the IE browser. "Forced" IE 8 Standards mode is the same as IE 8 Standards mode except for the fact that DOCTYPE directives that would force Quirks rendering are ignored.

Differences Between IE 7 Standards Mode and True IE 7

Features in IE 8's IE 7 Standards mode were designed to closely mimic the behavior found on pages loaded in IE 7. The rearchitecture of IE 8 in terms of browser interoperability caused a few compatibility breaks that could lead to errors in web applications built for IE 7 and using the IE 7 Standards mode equivalent in IE 8 (see Table 2-5).

Table 2.5. Differences Between True IE 7 Rendering and IE 8's IE 7 Standards Mode

Affected Area

IE 7

IE 8's IE 7 Standards Mode

Workaround

Attribute ordering

Item indices of an object's attribute collection were consistently correlated to certain named attributes.

Item indices of an object's attribute collection may not correlate to a specific attribute.

Access object attributes by name; replace instances where an object attribute collection is accessed through array indices.

CSS exception handling

Exceptions were thrown when accessing an invalid CSS object property.

No exceptions are thrown when accessing an invalid CSS object property.

Don't rely on invalid CSS accesses to throw exceptions; only use valid properties from markup and script.

Compatibility View

Compatibility View is a mechanism for displaying web sites designed for older versions of IE without hindering IE's long-term adoption of interoperable web standards. In short, it lets IE move forward without "breaking the Web," as the IE team has stated. Compatibility View is built upon a few basic tenets:

  • By default, all web pages run in IE 8 Standards mode ("standards by default").

  • Pages loaded through Compatibility View are run in IE 7 Standards mode.

  • When loading pages in Compatibility View, the User Agent string and conditional comments indicate the browser is IE 7.

  • Compatibility View is applied to an entire domain, including subdomains.

Unless a page has explicitly defined its document mode through the X-UA-Compatible <meta> tag or HTTP header, a web page will be displayed in Compatibility View if one of the following is true:

  • Its domain is present in the user's Compatibility View settings list (added by clicking the Compatibility View button or though manual insertion in Compatibility View Settings)

  • Its domain is present in the Compatibility View Group Policy key

  • Its domain is present in the Microsoft Compatibility View List

  • Its domain is in the Intranet zone, and Compatibility View is enabled for all intranet sites

  • Compatibility View is turned on for all web sites

The Microsoft Compatibility View List

At the time of IE 8's release, many commonly used web sites were broken when run in IE 8 Standards mode. Microsoft believed that this would prevent users from everyday browsing once IE 8 was installed on their systems. The Microsoft Compatibility View List was created to mitigate this scenario; this list contains the domains of popular web sites that render better in IE 7 Compatibility mode. Any domain on this list is loaded in Compatibility View until the site owner takes steps to ensure compatibility with IE 8 and/or requests removal.

Microsoft first released the Compatibility View List to users during the IE 8 Release Candidate. This list is sent using Windows Update, and can be downloaded separately through the Microsoft Download Center. Users wishing to download the list must opt into receiving and installing it. Developers should not depend on users doing so, as not all will install the list.

The list itself is an XML document implementing the ie8compatlistdescription namespace. Domains placed on the list are stored as strings within <domain> tags. The XML document is contained in an IE resource library (res://iecompat.dll/iecompatdata.xml) (Listing 2-6).

Example 2.6. Selection of Domains from the Compatibility View List (As of October 2009)

<?xml version="1.0" encoding="utf-8" ?>
<ie8compatlistdescription
   xmlns="http://www.microsoft.com/schemas/ie8compatlistdescription/1.0">
   ...
   <domain>americanexpress.com</domain>
   <domain>americangreetings.com</domain>
   <domain>amtrak.com</domain>
   ...
</ie8compatlistdescription>

Controlling Compatibility Settings

Domains displayed in Compatibility View can be controlled by users and developers through a number of exposed entry points. This feature is most accessible through the Compatibility View button, a toggle button displayed in the address bar when the feature is available (see Figure 2-2). Compatibility View can be switched on and off for any domain by clicking this button; this event will cause a domain to refresh into the desired state.

Compatibility View button in the IE address bar

Figure 2.2. Compatibility View button in the IE address bar

The Compatibility View button will always show up for a web page unless one or more of the following criteria are met:

  • The page is an IE resource file (the res:// protocol).

  • The page uses the X-UA-Compatible <meta> tag or HTTP header.

  • The page resides on the intranet and IE is set to use Compatibility View on all intranet sites.

  • IE is set to view all pages in Compatibility View.

  • The page's domain is included in the Microsoft Compatibility View List.

  • The Compatibility View itself or the button is turned off through the registry or Group Policy.

Developers who do not want this button to display can use the X-UA-Compatible header to explicitly define their page's document mode.

The Compatibility View Settings dialog (Figure 2-3) provides users with control over the use of the Compatibility View feature. Users can manually add and remove entries from this list, control usage of the Microsoft Compatibility View List, and apply Compatibility View throughout the intranet or all web sites.

Compatibility View Settings dialog

Figure 2.3. Compatibility View Settings dialog

Domains added through the Compatibility View Settings dialog are stored in a registry entry constructed as a proprietary binary blob with no public API. Developers wishing to add to this list can do so using the Group Policy key found at HKEY_CURRENT_USERSoftwarePoliciesMicrosoftInternet ExplorerBrowserEmulationPolicyList. A domain to be included in the list must be a REG_SZ string value whose value and data are equal, and must store the domain to be added (e.g., REG_SZ "mydomain.com"="mydomain.com"). System administrators can use the same key through their Group Policy Administration applications to apply a preselected list to networked machines.

Version Targeting

Not every page needs to target a document mode to mimic downlevel versions of IE. As developers test their web applications on new IE releases, some may find that their code works properly except in a few areas of script and markup. These testing scenarios also apply to functionality differences between IE and other browsers; portions of code may work in other browsers but not in IE.

Version targeting allows developers to customize sections of script or markup for specific browsers or browser versions. Instead of creating new web pages or web applications for each different scenario, developers can select and target code sections to specific scenarios.

Version Targeting Using Conditional Comments

Markup languages such as HTML and XML aren't designed for functional or conditional programming—their job is to define a document construct. This leads to problems when multiple versions of a markup language exist in the wild; documents would have to exist for every supported version of the markup language itself to provide full compatibility. IE introduced conditional comments in order to provide document compatibility within HTML.

Conditional comments are specially formatted HTML comments that IE uses to allow for targeted markup based on conditional logic. Developers wishing to target HTML content toward one or more specific versions of IE and/or non-IE browsers can wrap markup with these comments. When parsing a web page, IE will read any conditional comments present on a page and either use or ignore encapsulated markup based on the condition present.

Every conditional comment begins with an expression describing the condition. Contents of the comment are encapsulated in brackets, and within those brackets lies the if keyword followed by an expression. Any HTML to be used conditionally is placed after this tag, followed by a closing comment containing the endif keyword in brackets.

There are two main types of conditional comments (described in Table 2-6): downlevel hidden and downlevel revealed. A downlevel-hidden conditional comment is one that is recognized by IE and ignored by other browsers; the comment starts and ends with --, so it is treated as a traditional multiline markup comment. A downlevel-revealed conditional comment is one that is always used by non-IE browsers, but only used by IE versions that meet the conditional expression.

Table 2.6. Types of Conditional Comments

Type

Construct

Description

Downlevel hidden

<!--[if expression]> HTML <![endif]-->

Content is recognized only by IE versions that match the expression. It is ignored by non-IE browsers.

Downlevel revealed

<![if expression]> HTML <![endif]>

Content is recognized by non-IE browsers. Only IE versions matching the expression use enclosed content.

The combination of downlevel-hidden and downlevel-revealed conditional comments allow for one web application to provide both compatible and interoperable markup without the need to build separate applications or use script.

Expressions are conditional statements that consist of features, operators, and values. Features are known product names (e.g., IE and WindowsEdition) or custom feature names defined in the registry (see Table 2-7).

Table 2.7. Features for Conditional Commenting

Feature

Description

Example

IE

Internet Explorer

<!--[if IE 8]>

WindowsEdition

Windows product type from the GetProductInfo() API's pdwReturnedProductType

<!--[if WindowsEdition 1]>

(Custom)

Custom feature defined in a REG_SZ value and placed in the Version Vector registry key located at HKEY_LOCAL_MACHINESoftwareMicrosoftInternet ExplorerVersion Vector

<!--[if MyExtension gte 5]>

Operators are logic representations used to compare a value to a feature. Values are numerical representations of a feature version, stored as floats. (See Table 2-8.)

Table 2.8. Operators for Conditional Commenting

Operator

Description

Example

(Empty)

Equal to or exists

<!--[if IE]>

!

Not equal to

<!--[if ! IE 8]>

lt

Less than

<!--[if lt IE 8]>

lte

Less than or equal to

<!--[if lte IE 8]>

gt

Greater than

<!--[if gt IE 8]>

gte

Greater than or equal to

<!--[if gte IE 8]>

&

And

<!--[if (gte IE 5)&(lt IE 8)]>

|

Or

<!--[if (IE 8)|(gte WindowsEdition 4)]>

An expression can be defined either using a feature alone or as an ordered group of feature, operation, and value; feature-only expressions evaluate to true or false based on the feature's presence. Much like conditionals in traditional programming languages, multiple expressions can be grouped together using parentheses.

Conditional comments can be used anywhere within an HTML document. Common use cases include offering different stylesheets for specific IE versions and displaying messages to users of specific browsers. In the example in Listing 2-7, a web page serves two different CSS files to users: one that uses standards-based CSS that is interoperable in newer browsers such as IE 8 and Firefox 3.5, and another that offers a stylesheet focused on downlevel compatibility with older versions of IE.

Example 2.7. Using Conditional Comments to Target Different IE Versions and Browsers

<head>
   <title>Compatible and Interoperable!</title>
   <meta http-equiv="X-UA-Compatible" content="IE=8" />
   <![if gte IE 8]>
      <link rel="stylesheet" type="text/css" href="interoperable.css" />
   <![endif]>
   <!--[if IE 7]>
      <link rel="stylesheet" type="text/css" href="legacyIE.css" />
   <![endif]-->
</head>

Users browsing this example web site with IE 7 or IE 6 would be served legacyIE.css. All other users (e.g., those running IE 8, Firefox 3.5, and Safari 4) would see styles that were generated from interoperable.css.

Just like expressions, conditional comments can be nested. Nested comments are used for comparing multiple features and providing combinatorial markup paths. The sample in Listing 2-8 displays a different messages for users that are running IE 8 on Windows Ultimate, those running IE 8 on other Windows editions, and those users not running IE 8 at all.

Example 2.8. Nesting Conditional Comments

<body>
   <!--[if gte IE 8]>
      <![if WindowsEdition 1]>
         <b>You're running IE8+ on Windows Ultimate Edition!</b>
      <![endif]>
      <![if ! WindowsEdition 1]>
         <b>You're running IE8+, but NOT on Windows Ultimate Edition!</b>
      <![endif]>
   <![endif]-->
   <![if ! IE 8]>
      <b>You're not running IE 8 :(</b>
   <![endif]>
</body>

User Agent String Sniffing Using JavaScript

User Agent (UA) string sniffing is an unreliable (but often used) mechanism for delivering content for specific browsers, browser versions, or system configurations. Sniffing consists of reading and interpreting the UA string sent by a browser and serving content based on that interpretation. The concept itself is flawed for a few reasons: there are thousands of different configurations (and thus as many UA strings), these strings can be changed or spoofed by any application or person requesting a page, and they are very dynamic between browsers and even between browser versions. IE 8, for instance, even changes the UA string when running in Compatibility View vs. IE 8 Standards mode! If used improperly, the wrong content can be served to the wrong set of users. UA string sniffing should only be used in cases where it is absolutely necessary.

That said, developers can target certain portions of JavaScript to address compatibility issues between IE versions and interoperability issues among all browsers. Version targeting in JavaScript starts with getting the current browser type and version from the UA string. Regular expressions or string-parsing methods can be used to grab the name and version of the browser viewing a page.

In Listing 2-9, the GetIEVersion() function provides information on the version of IE the page is loaded in. If the page is loaded in IE and there is a version number present, the function returns the version number. If the browser is not IE or there is no version number, the function returns zero.

Example 2.9. Determining the IE Version Using JavaScript Regular Expressions

<script language="javascript" type="text/javascript">
   function GetIEVersion() {
      if (navigator.appName == "Microsoft Internet Explorer") {
         var regEx = new RegExp("MSIE ([0-9]+[.0-9]*)");
         if (regEx.exec(navigator.userAgent) != null)
            return parseFloat(RegExp.$1);
      }
      else return 0;
   }
</script>

Separate code paths can be created to target specific browsers and versions once that data can be determined. The GetIEVersion() function from the previous example returns this exact data. In the next sample, the result of calling that function is saved to the variable ieVersion. Conditional statements using that variable are created to create separate script paths for different browser and version requirements; in Listing 2-10, there is one path for IE versions before IE 8, and another for IE 8 and all other browsers.

Example 2.10. Creating Targeted Code Paths in JavaScript for Compatibility Scenarios

<script language="JavaScript" type="text/javascript">
   var ieVersion = GetIEVersion();
   if(ieVersion > 0 && ieVersion < 8) {
      // Place downlevel IE-compatible code here
      // (IE6, IE7, etc.)
   }
   else {
      // Place interoperable browser code here
      // (IE8, FF3, Chrome 2, etc.)
   }
</script>

Targeted script can be as granular as or as broad as required by compatibility and interoperability goals. In the preceding example, code separation using browsers and versioning creates a compatibility path (IE versions before IE 8) to address downlevel issues, and an interoperability path (IE 8 and other browsers) to take advantage of cross-browser web standards. Developers interested in expanding GetIEVersion() can do so by parsing the UA string for other browsers and applying the same logic to target code to those versions.

Compatibility View and the UA String

The UA string can be used to determine whether users are accessing web pages in Compatibility View or the most current IE standards mode. The UA strings in Listings 2-11 and 2-12 are generated by IE 8 and IE 8 with Compatibility View, respectively.

Example 2.11. UA String for IE 8 Running Normally

User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0;)

Example 2.12. UA String for IE 8 Running in Compatibility View

User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/4.0;)

While pages loaded in Compatibility View report MSIE 7.0 to be the current browser, the string still reports the rendering and layout engine to be Trident/4.0. Thus, developers wishing to gauge user access in IE 8 and compare total views to those using Compatibility View can do so. This metric allows developers to assess the impact and scope of Compatibility View on their application and, if necessary, plan to update them.

To reiterate, Compatibility View and the Microsoft Compatibility List are not designed to be long-term solutions for IE or for web pages. Developers should modify their web applications to migrate toward a more standards-based implementation for handling markup and script whenever possible.

The Web Developer's Dilemma

Compatibility and interoperability are in some cases mutually exclusive; getting the best of both worlds can be a challenge. The "innovator's dilemma," slightly modified for context, is quite relevant in relation to these competing concepts: should developers focus on compatibility and use known products to lower cost and increase profit, or should they embrace disruptive technologies that over time could also lead to attractive cost and profit deltas? Many developers, project managers, and industry leaders are faced with this very question, and each has their own opinions on it. Here are a few ways developers can make intelligent decisions about what route to take and how to ensure that applications will survive the tests of time and economy:

  • Migrate intelligently: Not every application needs to be migrated to use the latest and greatest web standards. This is especially true in certain enterprise situations, where migration could be costly; for example, many banks still use ages-old applications written in COBOL simply because they still just work. When considering possible routes to take with existing web applications, the costs and benefits of both compatibility and interoperability should be understood before changes are made.

  • Design with templates and frameworks in mind: Model-View-Controller (MVC) is a great example of how applications and systems can be designed to handle change while minimizing cost. There are a vast number of template systems (often in the form of content management systems [CMSs]) that allow for clear separation between content and structure, allowing a web application to easily change over time. Web frameworks such as jQuery and Dojo offer similar benefits as well; they seek to encapsulate functionality that allows web sites to remain both compatible and interoperable.

  • Develop against an appropriate standards baseline: HTML 5 is great, and it's packed full of awesome features. For a web site whose user base is filled with IE 6 and IE 7 users, it's not so great. Developers should choose a baseline set of standards that aligns with the goals (business or otherwise) of a web application.

  • Use version targeting wisely: Version targeting allows applications to remain compatible while pursuing a more interoperable design approach. Web applications using this method can serve content based on context, separate old code from new, and delimit functionality in a way that allows for easy deprecation over time. As discussed in this chapter, IE offers conditional comments that enable this behavior for markup. Outside of IE, developers can target specific browsers or versions through JavaScript and the UA string.

  • Realistically push modern browsers: The time for IE 6 has long past ... for those who use it without any specific reason. In some cases, there's a legitimate business reason to use an older browser. Developers should recognize that older browsers will represent a percentage of the market share for some time to come, and some may not have the luxury to ignore this constraint. While it's always an option to block users browsing to a site on IE 6, it might not be the best idea for a business that depends on their site to put food on employee's tables.

Clearly, this is not an all-encompassing list of things to consider when developing an application for compatibility and interoperability. Using web standards for the sake of web standards or staying compatible only to support a handful of users are not good reasons to make either decision. Consider the user base, purpose, intended platforms, and risk factors when deciding to develop for compatibility, interoperability, or some combination thereof.

Summary

I'll say it again: web development is hard. Those invested in web applications are in a constant struggle to deliver stellar functionality and meet design goals, all the while flying into a headwind of cost and effort caused by browser differences and endless compatibility scenarios. Web standards are helping to mitigate the problem, and IE 8's improved standards support can reduce the cost of developing sites that are compatible across modern browsers. IE 8 also offers a number of compatibility features that help ensure existing applications continue to work properly, giving you time to migrate applications to a standards-based model as needed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.80.15