IE 的條件注釋(Conditional Comments)可以讓你針對特定版本的 Internet Explorer 載入不同的資源,其他瀏覽器會把它當成一般的 HTML 註解直接跳過。
<!--[if IE]> <script type="text/javascript" src="resources/scripts/jquery.bgiframe.js"></script> <![endif]-->
上面這段程式碼只有在使用 IE 時才會載入 jquery.bgiframe.js。這一點很重要:把所有 hack 都無條件載入會白白浪費頻寬,頁面開啟速度也會變慢。
如果只需要處理 IE6,把條件改成 if IE 6 即可,例如修正 PNG 透明:
<!--[if IE 6]>
<script type="text/javascript" src="resources/scripts/DD_belatedPNG_0.0.7a.js"></script>
<script type="text/javascript">
DD_belatedPNG.fix('.png_bg, img, li');
</script>
<![endif]-->
也可以用它來為特定範圍的 IE 載入專屬樣式表。以下寫法會在 IE7 及更早版本中載入 ie.css:
<!--[if lte IE 7]> <link rel="stylesheet" href="resources/css/ie.css" type="text/css" media="screen" /> <![endif]-->
lt:小於(less than)lte:小於或等於(less than or equal)gt:大於(greater than)gte:大於或等於(greater than or equal)!:不為(not)搭配起來就能寫出 <!--[if !IE]>、<!--[if gte IE 8]> 這類條件,把相容性處理的範圍收在真正需要的地方。