Polyfills simplify the Javascript life, massively

Polyfills simplify the Javascript life, massively

How I learned to love polyfill

There are many JavaScript environments. And although JavaScript is standardised, the different environments still have very different functions.

Even if you limit yourself to the browser, you have to keep an eye on the different versions.

20 years ago, this was much more complex, but even now you have to deal with it as a developer.

deal with it

For a long time, a bad way to deal with these differences was to use navigator.userAgent to determine the browser and then use a browser switch.


let browser='unknown';

if (navigator.userAgent.indexOf("Firefox") > -1) {
  browser = 'Mozilla Firefox';
} else if (navigator.userAgent.indexOf("Opera") > -1 || navigator.userAgent.indexOf("OPR") > -1) {
  browser = "Opera";
} else if (navigator.userAgent.indexOf("Trident")) > -1) {
  browser = "Microsoft Internet Explorer";
} else {
  sBrowser = "unknown";
}

alert("Your browser: " + browser);

But this approach has always had many disadvantages. More effective is to check for a specific feature.

if ("geolocation" in navigator) {
  // use geolocation
} else {
  // Perhaps give the user a choice of static maps instead.
}

Doing this in your own codebase not only bloats the code, but also makes testing the codebase more costly.

A more effective way is to avoid polyfills in your own codebase and add missing features via external polyfills.

To avoid having to find and integrate every polyfill yourself, you can use services like polyfill.io.

These can inject the missing functions and objects for each browser.

With polyfill's URL builder, you can compile the polyfills you want.

You can also automate the creation of the URL. For this you can install the tool create-polyfill-service-url.

npm i create-polyfill-service-url

With the following call, the tool will analyse your script and throw out the desired URL.

npx create-polyfill-service-url analyse --file bundle.js

bundle.js here is the file that contains your code.

The result is a URL that you can simply into your HTML web page.

If you use external services like polyfill.io, you should remember that an additional HTTP request is required.

polyfill.io can also be self-hosted. On github you can find the repos for the service.

Have fun!

References