Polyfill
Code that implements a feature on browsers that don't support it natively, providing backwards compatibility for modern JavaScript features.
Overview
A polyfill is a piece of code (usually JavaScript) that provides modern functionality on older browsers that do not natively support it. While transpilers convert syntax, polyfills provide runtime implementations of missing built-in objects, methods, and APIs. They allow you to use modern JavaScript features while maintaining support for older browsers.
Example
javascript// Polyfill for Array.includes (not in IE11) if (!Array.prototype.includes) { Array.prototype.includes = function(searchElement) { for (let i = 0; i < this.length; i++) { if (this[i] === searchElement) { return true; } } return false; }; } // Now can use includes in older browsers [1, 2, 3].includes(2); // true // Using core-js for polyfills import 'core-js/stable'; import 'regenerator-runtime/runtime'; // Conditional polyfill loading if (!window.fetch) { // Load fetch polyfill import('whatwg-fetch'); } // Promise polyfill example if (!window.Promise) { window.Promise = require('promise-polyfill'); }
Key Points
- Adds missing features at runtime
- Different from transpilers (syntax vs features)
- Can increase bundle size
- Common: Promise, fetch, Array methods
- Tools: core-js, polyfill.io
Learn More
- Transpiler - Syntax conversion
- Babel - Can include polyfills
- MDN: Polyfill