由于 JavaScript API 有自己的规范,因此并非所有浏览器都同时支持特定规范。因此,我们必须提供 API 的补丁版本,以确保它仍然可以在不原生支持它的浏览器上运行。这种补丁称为 polyfill。
比如为 Safari 15.4 之前提供 Array 的at()
方法的补丁:
Array.prototype.at =Array.prototype.at ||function (index) {// The implementation ...};
又比如在Safari 15.4 之前 structedClone
不可用,也需要打上补丁:
typeof window.structuredClone !== 'function' &&window.structuredClone = function (value) {// ...};
出于为 CSS 属性添加前缀的相同原因,浏览器也在实验阶段为 JavaScript API 添加前缀。下表列出了最流行的浏览器的前缀:
前缀 | 浏览器 |
---|---|
moz | firefox |
ms | 使用 Chromium 引擎之前的 Internet Explorer 和 Microsoft Edge |
o | 使用 WebKit 引擎之前的 Opera 旧版本 |
webkit | Google Chrome、Safari、更新版本的 Opera 和 Edge 以及几乎所有的 iOS 浏览器 |
比如,针对requestAnimationFrame
函数:
window.requestAnimationFrame =window.requestAnimationFrame ||window.mozRequestAnimationFrame ||window.webkitRequestAnimationFrame ||window.oRequestAnimationFrame ||window.msRequestAnimationFrame;
全屏 API 则是更复杂的场景,支持全屏模式必须涵盖以下功能:
标准API | 描述 |
---|---|
fullscreenEnabled | 检查是否启用了全屏模式 |
requestFullscreen | 请求浏览器进入全屏模式 |
fullscreenElement | 返回全屏元素 |
fullscreenchange | 全屏模式发生时触发该事件 |
exitFullscreen | 退出全屏模式 |
首先需要一个支持该接口的包装器:
enum Api {ExitFullScreen,FullScreenChange,FullScreenElement,FullScreenEnabled,RequestFullScreen,
}type ApiMap = {[key in keyof typeof Api]: string;
};
针对不同浏览器,定义每个API的包装器:
const defaultVendor: ApiMap = {ExitFullScreen: 'exitFullscreen',FullScreenChange: 'fullscreenchange',FullScreenElement: 'fullscreenElement',FullScreenEnabled: 'fullscreenEnabled',RequestFullScreen: 'requestFullscreen',
};const webkitVendor: ApiMap = {ExitFullScreen: 'webkitExitFullscreen',FullScreenChange: 'webkitfullscreenchange',FullScreenElement: 'webkitFullscreenElement',FullScreenEnabled: 'webkitFullscreenEnabled',RequestFullScreen: 'webkitRequestFullscreen',
};const mozVendor: ApiMap = {ExitFullScreen: 'mozCancelFullScreen',FullScreenChange: 'mozfullscreenchange',FullScreenElement: 'mozFullScreenElement',FullScreenEnabled: 'mozFullScreenEnabled',RequestFullScreen: 'mozRequestFullScreen',
};const msVendor: ApiMap = {ExitFullScreen: 'msExitFullscreen',FullScreenChange: 'msFullscreenChange',FullScreenElement: 'msFullscreenElement',FullScreenEnabled: 'msFullscreenEnabled',RequestFullScreen: 'msRequestFullscreen',
};
最后就可以得到当前浏览器支持的API集,直接简单地调用给定元素的全屏AP即可:
const vendor: ApiMap =(Api.FullScreenEnabled in document && defaultVendor) ||(webkitVendor.FullScreenEnabled in document && webkitVendor) ||(msVendor.FullScreenEnabled in document && msVendor) ||defaultVendor;element[vendor.RequestFullScreen]();