HTML5特性检测应优先使用in操作符判断全局API存在性、typeof检测函数类型、创建元素试探行为,避免依赖UA或documentMode。
HTML5 本身没有统一的“检测支持”API,所有特性检测都依赖具体接口是否存在、能否执行或返回合理值。直接查 document.createElement('video').canPlayType 或 'localStorage' in window 比用第三方库更轻量、更可靠。
in 操作符检测全局 API 存在性这是最常用也最安全的方式,适用于 localStorage、sessionStorage、history、geolocation 等挂载在 window 上的 API。
in 只判断属性是否声明(包括 undefined),不触发 getter,无副作用typeof window.localStorage !== 'undefined' —— 在某些旧版 iOS Safari 中会抛错window.localStorage != null,因为未定义时会报 ReferenceError
if ('localStorage' in window) {
try {
localStorage.setItem('test', 'ok');
localStorage.removeItem('test');
} catch (e) {
// 私密模式下可能抛 QuotaExceededError
}
}
typeof 检测函数型接口对 URL.createObjectURL、fetch、IntersectionObserver 这类必须是函数才能用的特性,优先用 typeof 判断类型。
typeof fetch === 'function' 比 'fetch' in window 更准确:有些浏览器(如 IE11)有 fetch 属性但值为 undefined
new Audio().play 存在,但调用可能立即 reject,需结合实际调用测试Promise:ES6+ 环境中它必须是函数,但某些 polyfill 会把 Promise 设为 null 或对象if (typeof IntersectionObserver === 'function') {
const io = new IntersectionObserver(callback);
io.observe(target);
}
Canvas、Video、Audio、Form validation 等特性无法仅靠存在性判断,必须创建元素并试探其行为。
document.createElement('canvas').getContext('2d') 返回 object 才算真正支持 2D Canvasdocument.createElement('input').checkValidity 存在且为函数,不代表表单验证 UI 一定生效(如 Android WebView 可能静默忽略)audio.canPlayType('audio/mp3') 返回
''、'maybe' 或 'probably',空字符串即不支持该 MIME 类型const audio = document.createElement('audio');
const canPlayMP3 = audio.canPlayType('audio/mpeg') !== '';
document.documentMode 或 UA 字符串做 HTML5 特性推断IE 的 document.documentMode 只反映文档模式,和 HTML5 支持度无关;UA 字符串不可靠,且现代浏览器已普遍禁用或伪造 UA。
navigator.userAgent,返回 Chrome/110.0.0.0document.documentMode 在 Edge Chromium 中始终为 undefined
真实环境里,哪怕 Modernizr 生成的检测结果,也要在目标设备上实测关键路径。比如 iOS Safari 私密模式下 localStorage 会抛错,而大部分检测脚本根本跑不到那一步。