如何解决不同浏览器对 JavaScript API 的支持差异?


问题背景

不同浏览器对 JavaScript 新 API(Promise、fetch、Map/Set、Array.prototype 方法等)的支持程度不同,需要兼容处理以确保代码在旧浏览器正常运行。


现有答案

1. Polyfill(推荐)

  • 作用:用 JavaScript 模拟浏览器不支持的 API
  • 常用库
    • core-js:最完整的 ES polyfill
    • es5-shim/es5-sham:ES5 API
    • whatwg-fetch:fetch API
// 检测并加载 polyfill
import 'core-js/stable';
import 'whatwg-fetch';

2. Babel 转译

  • 作用:将 ES6+ 语法转换为 ES5 语法
  • 原理:在构建时将新语法转换为旧语法
// 输入(ES6)
const arr = [1, 2, 3];
const doubled = arr.map(x => x * 2);
 
// 输出(ES5)
var arr = [1, 2, 3];
var doubled = arr.map(function(x) {
  return x * 2;
});

3. Feature Detection

  • 作用:检测浏览器是否支持某个 API
  • 实现typeofin 运算符
// 检测 fetch 支持
if ('fetch' in window) {
  // 使用 fetch
} else {
  // 使用 XMLHttpRequest 或 JSONP
}
 
// 检测 Promise 支持
if (typeof Promise !== 'undefined') {
  // 使用 Promise
} else {
  // 使用回调或 bluebird
}

4. 库/框架

  • 作用:封装了兼容性处理
  • 示例:jQuery、axios、bluebird

总结

方法适用场景推荐程度
BabelES6+ 语法转译⭐⭐⭐⭐⭐
core-jsES 标准库 polyfill⭐⭐⭐⭐⭐
whatwg-fetchfetch API polyfill⭐⭐⭐⭐
Feature Detection运行时检测⭐⭐⭐⭐

相关笔记