DEV Community

Cover image for How to load polyfills to handle Web Components?
Gabriel Mayta
Gabriel Mayta

Posted on • Updated on

How to load polyfills to handle Web Components?

In this article I will explain you how I handled the latest ES6 and Web Components features.
If you are starting to work with Web Components you should know that they are well supported by Chrome, Firefox, Safari and Microsoft announced this year that they are working to support them.
So you don't need to load polyfills statically, increasing the weight of the final package.

For this reason I created a specific bundle to load polyfills at runtime when browsers don't support it.
I listed the most used features split by types. Below you can find the code:

As you can see I created a function where I define my WC and then I used dynamic import to enable code splitting to load all polyfills. The file contains all features that I need like fetch, es6 and WC features. Check the code:

To enable code splitting with webpack you need to install the following package:

$ npm i --save-dev @babel/plugin-syntax-dynamic-import
Enter fullscreen mode Exit fullscreen mode

After that add the package in your babel setup (.babelrc or babel.config.js):

$  plugins: [
$   '@babel/plugin-syntax-dynamic-import'
$  ]
Enter fullscreen mode Exit fullscreen mode

This demo works without the help of polyfills in Chrome, Safari, Firefox and Edge

If you try to launch the application with IE11, you will see the polyfill loaded:

Polyfill loaded

If you need to see the code, below you can find the links of my repositories:

Are Web Components the future? I don't know but with the right approach you can build reusable components that work in all browsers without load polyfills if you don't need it.

Keep calm and code!

Top comments (2)

Collapse
 
thesdev profile image
Samir Saeedi

Web Components aren't supported by Edge caniuse.com/#feat=custom-elementsv1

Collapse
 
grandemayta profile image
Gabriel Mayta

Hi Samir, you're right I updated the post. Anyway at moment Microsoft are working to support Web Components.