A. L
A. L

Reputation: 12679

webpack - how to load a chunked polyfill file as necessary

So the recommended way to prevent loading polyfills if it's unnecessary is to put some logic in the <head> (original: https://webpack.js.org/guides/shimming/)

<script>
    var modernBrowser = (
        'fetch' in window &&
        'assign' in Object
    );

    if ( !modernBrowser ) {
        var scriptElement = document.createElement('script');

        scriptElement.async = false;
        scriptElement.src = './polyfills.bundle.js';
        document.head.appendChild(scriptElement);
    }
</script>    

However, as my files are chunked, it will not be consistent e.g. polyfills.b0d50a4c4d9ca24a9f43.js.

So what's the best way to implement this logic (in webpack or just in the index.html)

Note

I work with Vue, so maybe I could just import it in the App component?

E.g.

var modernBrowser = (
    'fetch' in window &&
    'assign' in Object
);

if ( !modernBrowser ) {
    require("polyfill")
}

Upvotes: 0

Views: 854

Answers (2)

Cosimo Chellini
Cosimo Chellini

Reputation: 1730

A great service is polyfill.io https://polyfill.io/v2/docs/ which, according to the calling browser, generates the right polyfill, very configurable

Upvotes: 1

felixmosh
felixmosh

Reputation: 35593

You shouldn't require the polyfill like you did, cause the code of the polyfill will be always inside your bundle.

You need to make a chunk out of it, using require.ensure or import() syntax.

There is an article about it in webpack docs.

The idea is to create a file with you check, and then lazy load the polyfill.

//app entry point import myFramework from 'myFramework';

var modernBrowser = ( 'fetch' in window && 'assign' in Object );

function bootstrapTheApp() {
   myFramework.bootstrap();
}

if ( !modernBrowser ) {
    import("polyfill").then(() => {
       //polyfill loaded
       bootstrapTheApp();
    })
} else {
   bootstrapTheApp();
}

Upvotes: 1

Related Questions