Loading polyfills conditionally & bundles

Viewed 199

I'm composing a small library (for the first time) that utilizes the Resize Observer API. However, I want to include the polyfill for browsers that don't support it, and only load it into the final build if it's required, though I'm not sure where to place the API check/module load, or if this method is the right way to do it.

Say I have my index file which is the main file exported with the library, should I add this statement outside the function definition like so:

// index.js
(async () => {
    if (!ResizeObserver in window) {
        const module = await import('resize-observer-polyfill');
        window.ResizeObserver = module.ResizeObserver
    }
}();

// main function exported
export default () => {
    function loadResizeObserver() {
        const ro = new ResizeObserver((entries) => {
            // ...
        })
    }
}

Is there a better way to compose something like this? How will this affect the build and what's included if a consumer installs the package (with and without native RO support?) First time publishing and realized I know nothing about it.

0 Answers
Related