什么是 Polyfill

理解 Polyfill 的概念及其在浏览器兼容性中的作用

问题

什么是 Polyfill?

解答

Polyfill 是用于实现浏览器不支持的原生 API 的代码。它让旧版浏览器能够使用新的 Web API。

例如,querySelectorAll 是现代浏览器支持的原生 API,但一些旧浏览器不支持。我们可以写一段代码来模拟实现这个功能:

// querySelectorAll 的 Polyfill 示例
if (!document.querySelectorAll) {
  document.querySelectorAll = function(selector) {
    var doc = document,
        head = doc.documentElement.firstChild,
        styleTag = doc.createElement('STYLE');
    head.appendChild(styleTag);
    doc.__qsaels = [];
    
    styleTag.styleSheet.cssText = selector + "{x:expression(document.__qsaels.push(this))}";
    window.scrollBy(0, 0);
    
    var elements = [];
    for (var i = 0; i < doc.__qsaels.length; i++) {
      elements.push(doc.__qsaels[i]);
    }
    head.removeChild(styleTag);
    return elements;
  };
}

关键点

  • Polyfill 用于填补浏览器对新特性的支持空白
  • 通过 JavaScript 代码模拟实现原生 API 的功能
  • 常用于解决浏览器兼容性问题
  • 使用前通常先检测浏览器是否已支持该特性