关于IE9中X-UA-Compatible失效的问题

今天在IE9中调试Wordpress主题的时候发现无论X-UA-Compatible如何设置,IE9都是用Quirks Mode渲染,好端端的W3C标准页面被硬生生渲染成IE5,惨不忍睹。而在F12工具中强制调成IE9标准渲染模式,全部正常。于是研究了一下问题在哪。

关于X-UA-Compatible和IE的Quirks Mode模式,Google一下有很多说明,这里有三篇很详细的文章[1][2][3]:

http://msdn.microsoft.com/en-us/library/cc288325(VS.85).aspx
http://www.fantxi.com/blog/archives/browser-mode/
http://blog.csdn.net/wingeek/article/details/6198996

先上我主题header.php的源码。这个源码是从官方自带主题twentyeleven修改而来的,结构没有什么变动:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<!--[if IE 9]>
<html id="ie9" <?php language_attributes(); ?> xmlns="http://www.w3.org/1999/xhtml">
<![endif]-->
<!--[if lte IE 8]>
<html id="ie" <?php language_attributes(); ?> xmlns="http://www.w3.org/1999/xhtml">
<![endif]-->
<!--[if !(IE)]><!-->
<html <?php language_attributes(); ?> xmlns="http://www.w3.org/1999/xhtml">
<!--<![endif]-->
<head>
	<meta http-equiv="X-UA-Compatible" content="IE=9" />
	<meta http-equiv="Content-Type" charset="<?php bloginfo( 'charset' ); ?>" />

 

上面第12行无论如何设置content都是无效的,IE9不会识别。   搜索了一下,发现有两种说法。一种认为在X-UA-Compatible之前必须至少有一个meta标签[4]。另一种说法是X-UA-Compatible之前不能有script标签[5],后一种说法应该是比较靠谱的,因为在官方的说明文章里有这么一句[1]:

The X-UA-Compatible header is not case sensitive; however, it must appear in the header of the webpage (the HEAD section) before all other elements except for the title element and other meta elements.

但问题是我源码的相应位置并没有script标签。迟疑很久,我怀疑是之前IE注释的问题,不仅如此,经过调试发现这些注释在IE中根本没有生效(IE注释的作用见参考资料[6])。于是试着把它去掉变成:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html <?php language_attributes(); ?> xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="X-UA-Compatible" content="IE=9" />
	<meta http-equiv="Content-Type" charset="<?php bloginfo( 'charset' ); ?>" />

 

一切恢复正常了。然后我把IE注释移到body标签,注释也生效了。

结论:为防止失效,X-UA-Compatible最好紧跟在head之后,之前不要有任何不标准的标签。

 

[1] Defining Document Compatibility. MSDN Library. Microsoft Corperation. http://msdn.microsoft.com/en-us/library/cc288325(VS.85).aspx
[2] doctype声明、浏览器的标准、怪异等模式. Kairyou’s Blog. http://www.fantxi.com/blog/archives/browser-mode/
[3] [Web开发] IE文档模式终极指南. WinGeek. IE浏览器开发, HTML5. CSDN.NET. http://css-tricks.com/132-how-to-create-an-ie-only-stylesheet/
[4] X-UA-Compatible 无效. 行者无疆. http://www.lewphee.com/notes/2011-05-20-165443.html
[5] IE8 X-UA-Compatible 失效?. 99css. http://www.99css.com/archives/463
[6] How To Create an IE-Only Stylesheet. Chris Coyier. CSS-Tricks. http://css-tricks.com/132-how-to-create-an-ie-only-stylesheet/

鱼尾Swing

国内某理工学校电子类专业85后。热爱PS,热爱WEB,对各种技术都好奇。平时看看动画,听听音乐,做爱做的事。作为工坊的工头,负责工坊的维护,操劳各种苦力工作。

More Posts - Website

Follow Me:
Twitter

2 Responses

Leave a Reply