DEV Community

Cover image for Polyfills can make developer life easier
Volker Schukai
Volker Schukai

Posted on

Polyfills can make developer life easier

There are many different Javascript environments. And even though Javascript is standardized, the different environments still have very different features.

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

One bad way to deal with these differences has long been 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);
Enter fullscreen mode Exit fullscreen mode

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

if ("geolocation" in navigator) {
  // Use geolocation
} else {
  // Give the user a choice of static maps instead perhaps
}

Enter fullscreen mode Exit fullscreen mode

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

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

So that one does not have to search for and integrate each polyfill oneself, one can use services such as polyfill.io.

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

The URL builder from polyfill can be used to compile the desired polyfills.

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
Enter fullscreen mode Exit fullscreen mode

With the following call the tool analyzes your script and throws out the desired URL.

npx create-polyfill-service-url analyse --file bundle.js
Enter fullscreen mode Exit fullscreen mode

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

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

When using external services like polyfill.io, you should remember that an additional HTTP request is necessary.

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

hope you enjoy it!

References

Top comments (0)