通常我们提倡特性检测,但那是针对具体的功能开发的时候,如果要检测浏览器类型以及版本,就不应该使用特性检测了。例如我们经常检测IE6的代码是:
1 |
var isIE6 = !!window.XMLHttpRequest; |
我们不能排除第三方类库为IE6增加XMLHttpRequest方法,例如这个XMLHttpRequest兼容库。
所以应该使用userAgent代理字符串来检测浏览器,这个字符串就是为前后端提供环境识别的。
很多情况下,我们其实只需要识别出是否是IE,以及IE的版本,下面这一行代码就可以办到:
1 |
var isIE = +(navigator.userAgent.match(/MSIE (\d+)/) && RegExp.$1); |
然后就可以使用判断if(isIE){} 或者 if(isIE===6){}。
但是,以上代码并不能识别IE11及以上版本,因为IE11修改了userAgent 字符串,不再包含MSIE的标识。
IE11的意思是,觉着自己高大上了,不能再和你们这群奇模怪样的屌丝IE6-10混了,也来like Gecko。
1 |
<span spellcheck="true">// IE 10 userAgent </span>"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.3; WOW64; Trident/6.0)"<span spellcheck="true"> // IE 11 userAgent </span>"Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko"<span spellcheck="true"> // FireFox userAgent </span>"Mozilla/5.0 (Windows NT 6.3; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0"<span spellcheck="true"> // Chrome userAgent </span>"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36" |
IE11为了使自己更像一款现代浏览器,支持现行标准,丢掉包袱(查看 IE11 中的兼容性更改),使用老的特性检测或者老的代理字符串检测方式已经不能区分出IE11了,成功跻身到高富帅行列。
但是,IE11虽然IE家族中的高富帅,其余屌丝也得照顾,所以document.documentMode是万万不能丢的。这个IE独有的属性为我们提供了简便可靠的识别。因为document.documentMode本身就是标识IE浏览器文档模式的,所以不属于功能特性。
最终判断IE的代码:
1 |
var isIE = document.documentMode || +(navigator.userAgent.match(/MSIE (\d+)/) && RegExp.$1) |
转至Jony
- 本文固定链接: http://7iang.com/?p=374
- 转载请注明: 7iang 于 7iang 麦冰棍 发表