应直接检测功能是否存在而非猜测浏览器型号或版本,优先用typeof判断api是否为函数、css.supports()验证css特性、createelement测试html行为,并对可能报错的api加try/catch。

直接检测功能是否存在,而不是猜浏览器型号或版本。核心思路是:先试它有没有,有就用;没有就换方案或提示。
检测原生 API 是否可用
检查全局对象或 document 上的方法、属性是否定义且类型正确:
- 用 typeof 判断是否为函数,比
if (obj.method)更安全(避免值为 0、"" 等假值误判) - 例如检测
fetch:typeof window.fetch === 'function' - 检测
localStorage:typeof localStorage !== 'undefined' && typeof localStorage.setItem === 'function' - 检测
IntersectionObserver:typeof IntersectionObserver === 'function'
检测 CSS 特性是否生效
CSS 新特性(如 gap、inset、color-mix())不能靠 JS 属性存在性判断,必须用标准机制:
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
- 使用 CSS.supports(),支持两种写法:
CSS.supports('display', 'grid')或CSS.supports('(font-synthesis: none)') - 不推荐手动设样式再读取,容易受继承、重置、计算时机影响
- 可配合动态加载 polyfill:
if (!CSS.supports('contain: layout')) import('./contain-polyfill.js')
检测 DOM/HTML 特性是否被解析
某些 HTML 属性或事件行为需运行时验证:
- 检测
dialog元素:typeof HTMLDialogElement !== 'undefined' - 检测
input[type="date"]原生支持:const el = document.createElement('input'); el.type = 'date'; el.type === 'date' - 检测
beforeinstallprompt事件:'onbeforeinstallprompt' in window
处理可能抛错的 API
有些功能存在但调用会立即报错(如无权限、配额超限),需 try/catch 包裹:
- 例如
localStorage.setItem在隐私模式下会抛SecurityError - 写成:
try { localStorage.setItem('test', '1'); } catch (e) { /* 降级到内存 Map 或忽略 */ } - 同理适用于
Notification.requestPermission、navigator.geolocation.getCurrentPosition等
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










