Search code examples
web-componentrolluppolyfills

How to load polyfils from the CDN dynamically instead of bundling them into my code base?


I need to load the polyfill for my app to work on older browsers. I don't want to bundle the polyfills into my app but instead download them from cdn inside of my entry file and await them to be loaded before continuing with the rest of the code.

The official docs recommend installing as a dependency and adding the polyfill script tag before my application src code.

<!-- <script src="node_modules/@webcomponents/webcomponentsjs/webcomponents-loader.js"></script> -->

How can I go about loading that dynamically only continuing the execution once loaded?

I am using rollup with babel for bundling, and the polyfills are web components specific:

https://github.com/webcomponents/polyfills/tree/master/packages/webcomponentsjs#how-to-use

Also, my app is a web plugin that will also be loaded through a script tags from the CDN.


Solution

  • It's right on the page you linked.

    The webcomponents-loader.js is a client-side loader that dynamically loads the minimum polyfill bundle, using feature detection.

    The polyfill has an asynchronous loader module for your case (can also be used synchronously).

    Here's the code example from that page:

    <!-- Load polyfills; note that "loader" will load these async -->
    <script
      src="node_modules/@webcomponents/webcomponentsjs/webcomponents-loader.js"
      defer
    ></script>
    
    <!-- Load a custom element definitions in `waitFor` and return a promise -->
    <script type="module">
      WebComponents.waitFor(() => {
        // At this point we are guaranteed that all required polyfills have
        // loaded, and can use web components API's.
        // The standard pattern is to load element definitions that call
        // `customElements.define` here.
        // Note: returning the import's promise causes the custom elements
        // polyfill to wait until all definitions are loaded and then upgrade
        // the document in one batch, for better performance.
        return import('my-element.js');
      });
    </script>
    
    <!-- Use the custom element -->
    <my-element></my-element>
    

    Instead of applying the dynamic import in the callback only to my-element.js that would be the place where you import your components entry point.