skip to content

How does a usage-based polyfill injector choose what a web build adds, and why can it miss a method called through a computed property?

level: middleimportance: should knowfreq 8%

answer

  1. scan the code, not the browser
  2. entry import versus per-file imports
  3. matched by name, not by type
  4. runtime keys are invisible
  5. unscanned files get nothing

basics

~20 s

It scans each file it compiles for references to built-ins the target browsers lack, matched by name, and adds an import for each. A call like stopsmethod names no method in the source, so nothing is injected for it.

solid answer

~50 s

There are two strategies. Entry-based injection replaces a single import of the whole polyfill set at the entry with every polyfill the target browsers need, whether or not the code uses it: complete but heavy. Usage-based injection scans each file it compiles for references such as `Promise.withResolvers` or a `.at(` call and adds imports only for features the targets lack. Detection is static and name-based: `cart.at(0)` triggers the array polyfill even if `cart` is your own class, while `stops[method]()` with a key chosen at run time names nothing, so `findLast` is never added. It also misses files the build does not transform, which often includes dependencies, scripts loaded at run time and, in many setups, web platform APIs outside the language. Fix a miss by listing that polyfill explicitly, transforming the dependency, or switching to entry-based injection.

code

javascript · 10 lines
javascript
// departures.js as written
const { promise, resolve } = Promise.withResolvers();
const next = departures.at(0);
const method = showLatest ? 'findLast' : 'find';
const hit = departures[method]((d) => d.platform === 4);

// what a usage-based injector could prepend for an older target:
// import 'polyfills/promise-with-resolvers';
// import 'polyfills/array-at';
// nothing for findLast: the name never appears as a property access

go deeper

for a junior

Remember that polyfills can be added for the whole target gap at the entry, or only for what the code uses, and that the second relies on scanning the source.

for a middle

Explain the scan: names matched per compiled file against the targets, why it over-includes on instance methods, and why runtime keys and untransformed files are missed.

for a senior

Show how you trace a missing-polyfill crash to its source, decide between explicit polyfills, transforming a dependency or entry-based injection, and keep libraries from patching globals.

for a principal

Weigh bundle size against the risk of silent gaps across many apps, and decide whether polyfills belong in the build, in a shared baseline bundle or in a request-time service.

## Two ways to get polyfills into a bundle A **polyfill** supplies a built-in that an older engine lacks. A build can add polyfills in two broad ways, and both are driven by the **browser target**: a polyfill is only worth adding if some target browser is missing the feature. | Strategy | What it adds | Strength | Weakness | |---|---|---|---| | **Entry-based** | every polyfill the targets need, in place of one import at the entry | nothing the targets lack is missing | ships polyfills the code never calls | | **Usage-based, global** | imports for missing built-ins the scanned code references, patched onto the globals | small, follows the code | only as good as its detection | | **Usage-based, non-global** | the same detection, but call sites are rewritten to use imported helper functions | no global patching, suits libraries | helpers can be duplicated across packages | Entry-based injection still narrows by target: features that every target browser already supports are left out. ## How usage detection works A usage-based injector runs as part of the transform of each file: 1. Parse the file and walk its syntax tree. 2. Collect references that look like built-ins: global names (`structuredClone`, `Promise`), static members (`Promise.withResolvers`) and **instance method names** (`.at(`, `.findLast(`, `.flatMap(`). 3. For each one, look up whether any target browser lacks it. 4. Prepend an import of the matching polyfill module for every missing one, so it runs before the file's own code. The key word is **static**. The injector reads source text; it never runs the code and never sees a visitor's browser. Order matters as well. Because the polyfill imports are prepended to the file that uses the feature, module evaluation order runs them before that file's own code. A polyfill that arrives later, for example from a separate script tag placed after the bundle, is too late for code that calls the built-in during start-up. ## Why it over-includes For an instance method, the injector cannot know the type of the receiver. `cart.at(0)` might be an array, a string or your own `Cart` class with an `at` method. A safe injector therefore matches on the **name** and adds the polyfill anyway. The cost is a few unneeded bytes; a well-written polyfill only defines a method when it is missing, so your own class is not affected. ## Why it misses The same static, per-file design explains every miss: - **Computed property access with a runtime key.** In `departures[method](isOpen)`, where `method` is `'findLast'` or `'find'` depending on state, the name `findLast` never appears as a property access. Some injectors read a literal key such as `obj['at']`, but a key computed at run time cannot be resolved by static scanning. - **Files the build does not transform.** Many builds skip some or all third-party packages for speed. A dependency calling `.at()` gets no polyfill if its files are never scanned. - **Code loaded at run time.** A third-party script tag or a module fetched from another origin never passes through your build. - **Features outside the polyfill set.** Injection often covers ECMAScript built-ins only; web platform APIs may have to be added by hand. ## Global versus non-global injection Global injection patches `Array.prototype` and friends for the whole page. That is what an application wants: one consistent environment. A **library** should usually not do that, because it would change built-ins underneath the host app and can clash with the app's own polyfills. Non-global injection rewrites the library's calls into calls of imported helper functions, leaving globals untouched; the price is that two libraries may each carry their own copy. ## Fixing a miss When a field report says `departures.findLast is not a function` despite usage-based injection: 1. Find where the call comes from: your source, a dependency, or a script outside the build. 2. If it is your source and the key is dynamic, list that polyfill explicitly, or rewrite the call so the name appears. 3. If it is a dependency, include that package in the transform, or add its polyfills explicitly. 4. If the gaps are many or unpredictable, switch to entry-based injection and accept the extra bytes. A request-time polyfill service that picks polyfills from the visitor's user agent is a third design, outside the build entirely; it trades a network dependency for sending modern browsers nothing.

  • Why would a library author avoid injecting polyfills into the global scope?
    Global injection patches built-ins such as `Array.prototype` for the whole page, so a library doing it changes behaviour underneath the host app and can clash with the app's own polyfills. Non-global injection rewrites the library's call sites to call imported helper functions instead, leaving globals untouched. The cost is that each library may carry its own copies, while the app still decides what the page supports.
  • When is entry-based injection the safer choice despite the size?
    When you cannot trust detection: dependencies the build does not transform, code that calls methods through runtime keys, or scripts loaded later. Entry-based injection adds every polyfill the targets need regardless of usage, so nothing they lack is missed, at the price of shipping polyfills the code never calls. Its size still shrinks as the target moves newer.

  • The injector checks each visitor's browser and adds only what it lacks.
  • Usage-based injection knows the type of the object a method is called on.
  • If a polyfill were needed, the injector would certainly have added it.
  • Usage-based injection also covers dependencies the build never transforms.
  • Entry-based injection only adds polyfills the code actually calls.