What are Javascript Polyfills?

avatar

Borislav Hadzhiev

Sat Nov 28 20201 min read

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.

Add me on LinkedIn

I'm a Web Developer with TypeScript, React.js, Node.js and AWS experience.

Let's connect on LinkedIn

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee