Getting React to Load polyfills only when needed

Introduction

As a front-end developer, providing support to different browsers and devices isn’t an easy task. In fact, it’s the trickiest part of web development because there are differences in terms of HTML, CSS and JavaScript functions supported for every browser / device.

There are quite good web sites documenting these differences in terms of:

Anyways, if we already know that, and we are newbies on React, and like to apply some polyfills to our React application using a feature detection / dynamic / only load when needed strategy. Then I will quick show how to do it possible easily.

I am taking some assumptions:

  • You want to isolate your app code from the browser supported features (applying polyfills)
  • You have to add polyfills to yout web application because requires support to different browsers and devices
  • You want to use polyfill service like polyfill.io instead of including the polyfills in your bundle
  • You want (should) to load polyfills only when needed
  • You want to optimize the experience for users on modern browser
  • You want to save the polyfill service call when possible (using this polyfillLoader)

How to load polyfills only when needed

Here is the code:

 

IMPORTANT

  • I am using an npm package that wraps feature detection code and do polyfill.io call only with non supported features to be polyfilled: https://www.npmjs.com/package/polyfill-io-feature-detection
  • That function isn’t limited only to React, so you can use whatever technology which uses JavaScript.

 

Usage Samples

I used this polyfill loader in some Github projects:

 

 

Author: José Quinto
Link: https://blog.josequinto.com/2017/01/20/getting-react-to-load-polyfills-only-when-needed/
Copyright Notice: All articles in this blog are licensed under CC BY-SA 4.0 unless stating additionally.