Open In App

How to use polyfill in JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

The web has surfaced with a wide range of new technologies in recent years. As new technologies emerge, older browsers may not immediately support them. There is a wide variety of browsers and browser versions worldwide, each with slightly different features. While the latest versions of popular browsers can do many tasks older ones cannot, it may still be necessary to support the older versions. It can be challenging to integrate all of the latest features into the browser, ensuring our apps work efficiently without compromising the functionality of new ones.

Fortunately, Polyfill got developers covered. A polyfill provides the functions and features that the developer expects the browser to offer by default. Polyfill was coined by Remy Sharp. Basically, he wanted a term to describe reproducing an API using JavaScript (or Flash or whatever), if the browser does not have it natively.

Polyfill and its features:

  • Poly means that it could be solved using a wide range of techniques it wasn’t limited to just being done using JavaScript, and fill would fill the gap in the browser where the technology was needed. Polyfill can be seen as a material that fills the voids and cracks to smooth out any imperfections.
  • The ES6 release introduced many new features that are not yet fully supported by all browsers. If we use ES6 or ES7 or ES8 features in our code, it might not work in some older browsers due to a lack of support for the new features. Besides syntax constructs and operators, new language features may also include built-in functions. Thus, we use polyfill along with a transpiler. A polyfill is a piece of code that adds functionality to older browsers that have incompatibility issues.

In older browsers, the following features require polyfill support by explicitly defining the functions:

Promises, Array.from, Array.includes, Array.of, Map, Set, Symbol, object.values, etc

How to use polyfill in javascript? 

We will explore how polyfill works in node.js in this article. 

Approach: We will use promises. We will be writing the promises in ES6 code and then converting it into ES5 code to avoid the incompatibility issues of older browsers. We will then add this ES5 code babel polyfill file from our node modules to our index.html file to run the code in our browser. 

Step 1: Environment setup

A Babel transpiler is a free, open-source tool that converts ECMAScript 2015 (ES6) code to a backward-compatible version of JavaScript that can run on old and new browsers.  

We’ll set up our project and look at the Babel polyfill.

  • Make sure you have Node.js installed on your machine to run Babel polyfill.
  • Create a new project directory and run the following command in your terminal to get started:npm init -y 

Initializing npm 

  • Run the following command to install the babel cli, core and preset.
npm install @babel/cli @babel/core @babel/preset-env --save-dev

Package.json: It will look like this.

package.json file

  • Babel-polyfill gets installed along with the babel-core package.
  • Additionally, we will add es2015 to the predefined presets since we’re exploring how babel-polyfill converts our code to work on older browsers.

Now create a file .babelrc and add the following preset:

{ "presets":["@babel/env"] }
.babelrc file 

Step 2: Create a promises.js file and write the following code. This displays features of polyfill and promises and the console logs the greeting message after an interval of 3 secs. 

Javascript




// ES6 promises
  
const greet = new Promise((resolve, reject) => {
    setTimeout(function () {
        resolve("Welcome to GeeksforGeeks!");
        document.getElementById(
            "one"
        ).innerHTML = `Poly means that it could be 
        solved using a wide range of techniques it 
        wasn't limited to just being done using 
        JavaScript, and fill would fill the gap in 
        the browser where the technology was needed.`;
        document.getElementById(
            "two"
        ).innerHTML = `A polyfill is a piece of code 
        that adds functionality to older browsers 
        that have incompatibility issues.`;
        document.getElementById(
            "three"
        ).innerHTML = `In older browsers, Promises, 
        Array.from, Array.includes, Array.of, Map, 
        Set, Symbol, object.values, etc require 
        polyfill support by explicitly defining 
        the functions`;
        document.getElementById("four").innerHTML =
            "Promises represent uncompleted operations.";
    }, 3000);
});
  
greet.then((msg) => {
    console.log(msg);
});


Step 3: Convert the ES6 promises to ES5 code by running the following command in your terminal:

npx babel <ES6 code file name> --out-file <ES5 code file name>
npx babel promises.js --out-file promises_es5.js

Output: This will create a file promise_es5.js that contains the converted code. 

The es6 code is converted into es5 code 

Step 4: We need to include polyfill along with the final compiled ES5 code. 

Create an index.html file and add a heading with <h1> tag. The features of polyfill in the <li> tag and the description about Promises in <h4> tag will be displayed after the interval of 3 secs. We will add the babel-polyfill file from node modules to the index.html file where we want to use promises to run the code in the browser. 

<script type=”text/javascript” src=”node_modules/babel-polyfill/dist/polyfill.min.js”></script>
<script type=”text/javascript” src=”/promises_es5.js”></script>

Add the following code to the index.html file. 

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" 
          content="IE=edge">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Polyfill</title>
</head>
<body>
    <h1 style="text-align: center;color: green;">
      Welcome to GeeksforGeeks : Polyfill testing
    </h1>
    <h1 style="text-align: center;color: green;"
      Polyfill-Features
    </h1>
    <h3>(The features will be displayed after 3 secs)</h3>
    <ul>
        <li id="one">
        </li>
        <li id="two">
  
        </li>
        <li id="three">
  
        </li>
    </ul>
    <h4>We have used promises to understand how to use polyfill</h4>
    <h1>Promises</h1>
    <h4 id="four"></h4>
    
    <!-- Polyfill.min.js file from node_modules and promise_es5 -->
    <script type="text/javascript" 
            src="node_modules/babel-polyfill/dist/polyfill.min.js">
    </script>
    <script type="text/javascript"
            src="/promises_es5.js">
    </script>
</body>
</html>


Our final project structure: It will look like this.

Project structure 

Step to run our application: To start a server, right-click on your index.html file and select an open live server. 

Output: Using polyfill, we’re able to use promises. The features of polyfill along with a brief description of promises will be displayed after an interval of 3 seconds. 

Now refresh the browser. Use the inspect option or press ctrl + shift + i to open the console window. A greeting message will appear after an interval of 3 seconds in the console window. 

Output: Using es6 promises with the help of polyfill 

Reference: https://developer.mozilla.org/en-US/docs/Glossary/Polyfill



Last Updated : 16 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads