front-end-interview-handbook/packages/quiz/questions/whats-the-difference-betwee.../zh-CN.mdx

34 lines
1.2 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: 特性检测、特性推断和使用 UA 字符串有什么区别?
---
## 特性检测
特性检测涉及确定浏览器是否支持某段代码,并根据是否支持运行不同的代码(或不支持),以便浏览器始终提供工作体验,而不是在某些浏览器中崩溃/出错。例如:
```js
if ('geolocation' in navigator) {
// 可以使用 navigator.geolocation
} else {
// 处理缺少的功能
}
```
[Modernizr](https://modernizr.com/) 是一个处理特性检测的好库。
## 特性推断
特性推断像特性检测一样检查特性,但使用另一个函数,因为它假定它也将存在,例如:
```js
if (document.getElementsByTagName) {
element = document.getElementById(id);
}
```
这真的不推荐。特性检测更万无一失。
## UA 字符串
这是一个浏览器报告的字符串,它允许网络协议对等方识别请求软件用户代理的应用程序类型、操作系统、软件供应商或软件版本。可以通过 `navigator.userAgent` 访问它。但是该字符串很难解析并且可以被欺骗。例如Chrome 报告为 Chrome 和 Safari。因此要检测 Safari您必须检查 Safari 字符串以及 Chrome 字符串的缺失。避免使用此方法。