Polyfill

On this page 7

A polyfill is a piece of code, usually JavaScript, that implements a standard web platform feature in a browser that does not support it natively, so that application code can call the same standard API in every environment. In Browser JavaScript and across the Web, polyfills bridge the gap between what specifications define and what older or less common browsers actually ship.

The term was coined around 2009 by analogy with a filler paste that smooths uneven walls: the polyfill fills the holes in browser support until the surface looks uniform to the developer. When native support arrives, a well-written polyfill steps aside automatically and the browser uses its own implementation.

How a polyfill detects and fills a missing feature

A polyfill works in two steps: feature detection followed by conditional definition. It first checks whether the API exists, for example by testing typeof Promise or 'fetch' in window, and only if the check fails does it attach its own implementation to the global object or to a built-in prototype.

The polyfilled implementation must follow the specification closely, including edge cases, return types and error behavior, because the calling code assumes it is talking to the real API. A polyfill for Array.prototype.includes, for instance, must treat NaN correctly, which a naive loop with strict equality would not.

The table below summarizes the typical stages of a polyfill at load time.

StageWhat happensWhy it matters
DetectionCode tests whether the native API existsAvoids overwriting a faster native version
DefinitionA spec-compliant fallback is attachedApplication code can call the standard name
ExecutionApplication uses the API normallyOne code path for all supported browsers
RetirementPolyfill is removed when support is universalReduces bundle size and maintenance
Polyfill lifecycle in the browser

What a polyfill can and cannot provide

Polyfills can only add runtime APIs, meaning objects, functions and methods. They cannot add new syntax, because an older JavaScript engine fails to parse unknown syntax before any polyfill code runs.

Some APIs also depend on engine internals that script cannot reproduce. A Proxy object, true native lazy loading or precise memory semantics such as WeakRef cannot be faithfully recreated, and partial imitations can mislead developers into believing the behavior is identical.

FeaturePolyfillableReason
PromiseYesImplementable with callbacks and microtask emulation
Fetch APIYes, mostlyBuilt on XMLHttpRequest, with streaming limits
Intersection Observer APIYes, approximatelyEmulated with scroll events and geometry checks
Async/awaitNo, needs transpilingNew syntax that older parsers reject
ES modulesNo, needs bundlingLoader semantics live in the engine
ProxyNoRequires interception at the engine level
Typical features by polyfill feasibility

For features in the second group, the correct tool is a transpiler such as Babel or the TypeScript compiler, which rewrites new syntax into older syntax at build time. Real projects usually combine transpiling for syntax and polyfills for APIs.

Polyfill, shim, ponyfill and transpiler compared

Several related terms describe compatibility code, and they are not interchangeable. The distinction lies in whether the code follows a standard and whether it modifies global objects.

TechniqueFollows a standardModifies globalsTypical example
PolyfillYesYesAdding Array.prototype.flat to an old engine
ShimNot necessarilyOftenWrapping an API to normalize vendor differences
PonyfillYesNoImporting a standalone fetch function as a module
TranspilerYes, for syntaxNoConverting optional chaining into conditional checks
Compatibility techniques and their differences

A ponyfill is often preferred in libraries, because patching globals from a library can conflict with the host application or with another polyfill version. Application code, in contrast, benefits from true polyfills because they keep the standard names available everywhere.

Delivering polyfills efficiently

The main engineering question is which browsers receive which polyfills. Shipping every polyfill to every user wastes bandwidth and parse time on modern browsers that need none of them.

  • Usage-based injection: build tools such as Babel with a browser target list add only the polyfills that the code actually uses and that the targets lack.
  • Differential serving: a modern bundle is served through type="module" scripts and a legacy bundle with polyfills to older browsers.
  • Conditional loading: a small inline check loads a polyfill file only when detection fails.
  • Self-hosting: polyfill files are bundled or served from the same origin rather than from a third-party script service.

The browser target list, often written as a Browserslist query, is the single most important setting. Raising the minimum targets can remove tens of kilobytes of polyfill code, depending on how many features the project uses.

Risks and common mistakes with polyfills

Polyfills run with full access to the page, so they carry the same security weight as any other script. In 2024 a widely used third-party polyfill domain changed ownership and began serving injected malicious code to many sites, which showed the danger of loading compatibility code from an external host.

ProblemCauseFix
Broken native behaviorPolyfill overwrites an existing APIAlways guard definitions with feature detection
Supply-chain compromiseScript loaded from an external domainSelf-host and pin versions with integrity checks
Bloated bundlesAll polyfills shipped to all browsersUse target-based injection and differential serving
Subtle spec mismatchesIncomplete or outdated implementationUse maintained, tested polyfill libraries
Stale polyfillsCode kept after support became universalReview the target list regularly
Frequent polyfill problems and their fixes

Another mistake is assuming performance parity. A polyfilled API usually runs slower than the native one, and approximations such as an emulated observer may react later or less precisely than the real implementation.

The short version

Websites are written using features that browsers are supposed to understand. Older browsers sometimes do not know about newer features, so the page breaks. A polyfill is a small add-on that teaches an old browser a missing feature.

Think of it as a translator who steps in only when needed. If the browser already understands the feature, the polyfill stays quiet. The key idea: polyfills let one website work the same way in many browsers, but they cost a little extra download time and should come from a trusted source.

Where it makes a difference

A public transport company runs a ticket booking web application that must work on older smartphones still used by many passengers. Analytics show that about 6 percent of visits come from browsers without native support for Array.prototype.flat and Object.fromEntries, both of which the checkout code uses.

The frontend team sets its Browserslist targets to match real traffic and lets the build tool inject only the required polyfills into a separate legacy bundle. Modern browsers receive the lean module bundle, while older ones receive an extra file of roughly 20 kilobytes.

After the release, checkout errors from older devices drop to almost zero, and page weight for the majority of users stays unchanged. Because the polyfills are self-hosted with the rest of the bundle, no third-party script can alter them.