Introduction To Polyfills In Javascript

In this tutorial, you will learn how to ensure that the Javascript you write works in any browser.  In my last tutorial, I gave an introduction to Babel.  With ECMAScript 2015+ came a slew of new features - promises, fetch, arrow functions - all sort of goodness. 

When you test your JS in chrome, it will work.  When you test it in IE it doesn't.  When this happens you have a few options, never write Javascript that uses any new language features, maintain two or more Javascript files each catered to a specific browser, or use tools to make your new code work in older browsers. 

Out of those options, the easiest and best option is to let something convert your code into something an older browser will understand.  This is where babel and polyfills come in.  Sound interesting, then read on. 

Why Do I Need To Use A Polyfill And Babel?

Out of the box, Babel will 'transpile' your code.  Transpile is definitely one of those annoying technical terms that sounds complex but in reality is easy to understand.  When Babel transpiles your code, it will convert any syntax that older browsers won’t understand and turn into code that it will.

A second problem now exists.  Babel at its core will only ensure that a compiler can compile your script.  This doesn't mean that an older browser will understand that code.  Take a 'promise' for example.  Syntax-wise creating a new promise is valid Javascript syntax, so it would be transpiled.

If you try and run a promise in IE you will get an error.  This is where polyfills come into play.

What Is A Polyfill?

A polyfill is a bit of code that defines a new object or method in an older browser that doesn’t support that feature.  Promises, maps, fetch, includes(), padEnd(), requestIdleCallback() and URLSearchparams.  You can find a list of all polyfills W3C approved polyfills at polyfill-central.

To recap, if you want your code to work in older browsers you will need to transpile it and you will need to use polyfills.  The polyfill will make sure the older browser understands how a new object or method introduced in a language works.  The transpiler will make sure it can compile it.

Polyfills And Babel

When we work with babel, we can use the babel polyfill plug-in to do all of this for us.  Getting polyfill working in your solution is as simple as installing an NPMpackage. 

npm install babel-polyfill

 

 

submit to reddit

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

Back to top