Blog

Getting React to Load polyfills only when needed

image

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:

HTML and CSS: http://caniuse.com/

JavaScript / ES6 / Transpilers / Polyfills: https://kangax.github.io/compat-table/es6/

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)

Here is the code:

 

 

Notes:

– 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.

 

Samples

I used this polyfill loader in some Github projects:

React responsive menu

React and OpenLayers custom control

 

 

Hope that helps!

@jquintozamora

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

Post Navigation