What are Javascript Polyfills?


Borislav Hadzhiev

Last updated: Nov 28, 2020


Check out my new book

Being able to write modern code and ship to older browsers #

A polyfill is a piece of code (usually Javascript code) that is used to provide modern functionality to older browsers that don't natively support it.

For example - the polyfill for Object.assign has to provide the same functionality as the real function, however it takes 29 lines of code: Object.assign Polyfill

Only include polyfills for the browsers you want to support #

To keep our JavaScript bundles small we only want to provide polyfills for the browsers we want to support, i.e. IE11 and up. If you don't have to support IE, chances are your bundle is going to be way smaller.

Check if the method exists, before implementing it #

Always check to see if the method you are polyfilling exists, before overwriting it. For example trim() is a method that is not supported in very old IE versions:

if (typeof String.prototype.trim !== 'function') { String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,'') } } > " zebra ".trim() // "zebra"

Having written the conditional logic, you can have a script that runs before your code in your HTML document and runs these if checks to see whether the methods are supported. If they are supported - don't do anything, if they are not - implement them.

Use the search field on my Home Page to filter through my more than 3,000 articles.