![浏览器资源嗅探器](https://i-blog.csdnimg.cn/blog_migrate/904aa875d6f131c5feeb247ac523152b.png)
浏览器资源嗅探器
Browser sniffing is bad. But sometimes unavoidable. But doing it on the server is bad, because UA string is unreliable. The solution is to use conditional comments and let IE do the work. Because you're targeting IE most of the times anyway.
浏览器嗅探是不好的。 但有时不可避免。 但是在服务器上这样做很不好,因为UA字符串不可靠。 解决方案是使用条件注释,然后让IE完成工作。 因为无论如何,大多数情况下都是以IE为目标。
In fact IE8 is a decent browser for the most practical purposes and often you're just targeting IE before 8.
实际上,对于大多数实际用途而言,IE8是一款不错的浏览器,通常您只是将目标指向8之前的IE。
Conditional comments in practice use the following pattern:
实际上,条件注释使用以下模式:
- Load the decent browsers CSS 加载体面的浏览器CSS
- Conditionally load IE6,7 overrides 有条件地加载IE6,7覆盖
The drawback is that IE6,7 get two HTTP requests. That's not good. Another drawback is that having a separate IE-overrides stylesheet is an excuse to get lazy and instead of solving a problem in a creative way, you (and the team) will just keep adding to it.
缺点是IE6,7获得两个HTTP请求。 这不好。 另一个缺点是拥有一个单独的IE覆盖样式表是懒惰的借口,您(和团队)不会继续以创造性的方式解决问题,而是会继续添加它。
We can avoid the extra HTTP request by creating our CSS bundles on the server side and having two browser-specific but complete stylesheet files:
我们可以通过在服务器端创建CSS捆绑包并拥有两个特定于浏览器但完整的样式表文件来避免额外的HTTP请求:
- The decent browsers CSS 体面的浏览器CSS
- The complete CSS for IE6,7 not only the overrides IE6,7的完整CSS不仅覆盖
Then the question is loading one of the two conditionally without server-side UA sniffing. The trick (courtesy of duris.ru) is to use conditional comments to comment out the decent CSS so it's not loaded at all:
然后问题是有条件地加载两个服务器之一,而无需服务器端UA嗅探。 技巧(由duris.ru提供)是使用条件注释来注释出不错CSS,因此根本不会加载它:
<!--[if lte IE 7]>
<link href="IE67.css" rel="stylesheet" type="text/css" />
<![endif]-->
<!--[if gt IE 7]><!-->
<link href="decent-browsers.css" rel="stylesheet" type="text/css" />
<!--<![endif]-->
The highlighting suggests what the decent browsers see.
突出显示了不错的浏览器看到的内容。
IE6,7 see something like this after the conditional comments are processed:
在处理条件注释后,IE6,7会看到类似以下内容:
<link href="IE67.css" rel="stylesheet" type="text/css" />
<!--
<link href="decent-browsers.css" rel="stylesheet" type="text/css" />
-->
Tell your friends about this post on Facebook and Twitter
在Facebook和Twitter上告诉您的朋友有关此帖子的信息
翻译自: https://www.phpied.com/browser-sniffing-with-conditional-comments/
浏览器资源嗅探器