随着release of jQuery 2.0 ,已经有很多关于如何识别用户使用的 IE 版本是否支持它的讨论(jQuery 2.0 仅支持 IE9 及更高版本)。
我的问题是为什么像 this 这样的解决方案:
var ie = (function(){
var undef,
v = 3,
div = document.createElement('div'),
all = div.getElementsByTagName('i');
while (
div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
all[0]
);
return v > 4 ? v : undef;
}());
优于查看 navigator
对象:
function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
最佳答案
功能检测(在这种情况下,检测对条件注释的支持)是可靠的,因为您知道给定浏览器的给定版本已经以某种方式实现了给定功能。即使更高版本删除了此功能(在这种情况下,条件注释在 IE10 中被删除),它也不会改变以前版本实现它的方式。对于以前未实现但后来在较新版本中引入的功能也是如此。
使用标准时,特征检测通常也与 vendor 无关。您正在查看浏览器是否支持某项功能,而不管它是哪种浏览器。这有助于促进浏览器之间的互操作性,同时避免不必要的歧视。
另一方面,在使用用户代理字符串时,您依赖于可以以各种方式操纵的任意字符串的值,不仅可以由第三方或作者代码,甚至可以由用户代理本身。这个字符串很复杂并且难以解析,而且试图解析它的代码通常会以惊人的方式失败。这就是 UA 嗅探如此不可靠的原因。
modern.IE更好地解释缺点:
Always prefer feature detection over browser (navigator.userAgent) detection.
The userAgent string is a poor indicator of whether a particular feature (or bug) is present. To compound the problem, much of the code that interprets userAgent does so incorrectly. For example, one browser-sniffing library expected the major version to be only a single digit, so it reported Firefox 15 as Firefox 1 and IE 10 as IE 1! It is more reliable to detect the feature or problem directly, and use that as the decision criteria for code branches. We recommend Modernizr as the easiest way to implement feature detection.
关于javascript - 使用导航器对象/用户代理嗅探检测 IE 版本的缺点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16145067/