在js中检测浏览器的最佳方法 [英] the best way to detect browser in js

查看:168
本文介绍了在js中检测浏览器的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中有很多浏览器检测方法。

There are lots of ways for browser detecting in JavaScript.

据我所知,使用 navigator.userAgent 或检测功能(如 XMLHttpRequest )等等。

As far as i know, using navigator.userAgent or detecting features (like XMLHttpRequest) and so on.

任何人都可以告诉我哪种方式最好最有效的?

Can anybody tell me which way is the best and most effective?

推荐答案

如果你真的需要知道 浏览器 他们正在使用,你大多必须查看 userAgent 字符串(尽管你有时可以通过寻找一些不起眼的功能来推断浏览器)。请注意,有些浏览器会让用户更改并骗你。 : - )

If you really need to know what browser they're using, you mostly have to look at the userAgent string (although you can sometimes infer the browser by looking for a couple of obscure features). Just be aware that some browsers let the user change that and lie to you. :-)

但检测浏览器已经过时了,原因很充分。相反,正如您所说,您想要检测您正在寻找的功能。这更可靠,工作量更少。例如,仅仅因为IE不支持 addEventListener ,并不意味着它永远不会(事实上IE9确实如此)。所以你要进行功能检测,这将代码未来发展。

But detecting the browser is out of fashion, for good reasons. Instead, as you say, you want to detect the features you're looking for. This is more reliable, and less work. Just because IE didn't support addEventListener, for instance, doesn't mean it never will (and in fact IE9 does). So you feature-detect instead, which future-proofs the code.

这是一个具体的例子:假设你想知道(正如我为 place5 jQuery插件)浏览器是否支持 占位符属性。您可以使用浏览器检测并维护哪些版本具有或不具有支持的浏览器列表,这些浏览器是混乱的,您必须继续回访等等,或者你可以这样做:

Here's a concrete example: Suppose you want to know (as I did for my place5 jQuery plug-in) whether a browser supports the placeholder attribute. You could use browser detection and maintain a list of which browsers in which versions have or don't have support, which is messy and something you have to keep coming back to, etc., etc., or you could do this:

if ("placeholder" in document.createElement("input")) {
    // The browser supports the attribute
}
else {
    // It doesn't
}

...你已经完成了。

...and you're done.

此页面 kangax 。还有一个名为 Modernizr 的图书馆,可以为您提供特征检测,媒体查询等功能。如果你使用jQuery,它有一些内置的功能检测通过 jQuery.support 。在这篇文章

There's a great set of feature tests in this page maintained by kangax. There's also a library called Modernizr that does feature detection, media queries, and more for you. If you use jQuery, it has some feature detection built in via jQuery.support. There's a nice discussion of various aspects of feature detection, media queries, form-factor detection (tablet, phone, or PC?) in this article.

这篇关于在js中检测浏览器的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆