Life, the Universe, and Software EngineeringLife, the Universe, and Software Engineering

Generating “compatibility mode” safe HTML using Razor

Main Image

Internet Explorer has this "wonderful" feature call compatibility mode. I think the majority of web designers that have run into this gem would likely feel that Microsoft misnamed this feature.

After a great deal of frustration and delays caused by having the compatibility mode suddenly turn on and breaking our site we finally found a solution that works.

 

 

 

 

 

 

 

The site we have created was written in ASP.NET MVC 3 Razor, and we are running the latest version (2.5.2) of Modernizer. Our original _layout.cshtml file which had intermittent problems with Internet Explorer 8 switching to compatibility mode looked like the following:

<!DOCTYPE html class="no-js"> 
<!--[if lt IE 7]> <html class="no-js ie6 oldie" lang="en"> <![endif]--> 
<!--[if IE 7]> <html class="no-js ie7 oldie" lang="en"> <![endif]--> 
<!--[if IE 8]> <html class="no-js ie8 oldie" lang="en"> <![endif]--> 
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]--> 
<head> 
 <meta http-equiv="X-UA-Compatible" content="IE=Edge;" /> 
</head> 

 

Note that the <!--[if lt IE 7]> style xml comments are the "best practice" for supporting multiple IE browsers, letting the browser choose the best tag to use when the page is displayed.

Below is a snippet of the _layout.cshtml file which solves this problem and supports all of the older IE browsers:

<!DOCTYPE html> 
@if (Request.Browser.Browser == "IE" && Request.Browser.MajorVersion < 9) 
{ 
 if (Request.Browser.MajorVersion < 7) 
 { 
 @:<html class="no-js ie6 oldie" lang="en"> 
 } 
 else if (Request.Browser.MajorVersion == 7) 
 { 
 @:<html class="no-js ie7 oldie" lang="en"> 
 } 
 else if (Request.Browser.MajorVersion == 8) 
 { 
 @:<html class="no-js ie8 oldie" lang="en"> 
 } 
} 
else 
{ 
@:<html class="no-js" lang="en"> 
} 
<head> 
 <meta http-equiv="X-UA-Compatible" content="IE=Edge;" /> 
</head> 

 

 

Note that based on our testing, and contrary to other posts we have found, for "compatibility mode" to not turn on we must have a combination of the meta data tag X-UA-Compatible and the use of server side selection of the browser type. Any other combinations resulted in older browsers kicking into compatibility mode from time to time.

If you are not using Modernizer the _layout.cshtml file the markup becomes much simpler and more in line with other posted solutions:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
 <meta http-equiv="X-UA-Compatible" content="IE=Edge;" /> 
</head> 

Authors

All Categories

Archive