Loading a chunked polyfill file in webpack only when needed - a step-by-step guide

In order to prevent unnecessary loading of polyfills, it is recommended to add some logic in the <head> section (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, due to file chunking, consistency may not be maintained e.g.

polyfills.b0d50a4c4d9ca24a9f43.js
.

What would be the most effective way to incorporate this logic (in webpack or directly in the index.html)?

Note

Considering that I work with Vue, could importing it in the App component be a viable option?

For example:

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

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

Answer №1

Avoid directly including the polyfill in your bundle as it will unnecessarily increase its size.

Instead, create a separate chunk for the polyfill using either require.ensure or import().

You can refer to an informative article in the webpack documentation for more details.

The recommended approach is to check for browser compatibility and then lazily 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();
}

Answer №2

One fantastic solution I highly recommend is polyfill.io, offering a wide range of customizable polyfills based on the user's browser needs. Check it out at

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Vue.js to pass an image URL as a prop for CSS animation by converting it to a CSS variable

Need help with a component that features a hover animation displaying 4 rotating images: animation: changeImg-1 2.5s linear infinite; @keyframes changeImg-1 { 0%, 100% { background-image: url('images/wel1.png'); } 25% { background-image: ur ...

Tips for Managing Disconnection Issues in Angular 7

My goal is to display the ConnectionLost Component if the network is unavailable and the user attempts to navigate to the next page. However, if there is no network and the user does not take any action (doesn't navigate to the next page), then the c ...

Having trouble with $.ajax? I can't seem to get it to hit my controller action. Can anyone provide

Seeking assistance. I need help with the following code snippet: <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <script type="text/javascript> function GOTO() { var datastring = "id=2"; $. ...

Include the <script> tag in the HTML code for an iframe without running it

Currently, I am working on an HTML code that involves memory for an Iframe. Interestingly, whenever I use the append function, it not only executes the code but also carries out its intended task. html = $(parser.parseFromString($("#EHtml").val(), "text/h ...

transform a zipped file stream into a physical file stored on the disk

I have a Node application named MiddleOne that communicates with another Node App called BiServer. BiServer has only one route set up like this: app.get("/", (req, res) => { const file = `./zipFiles.zip`; return res.download(file); }); When Middl ...

Create a personalized form with HTML and JQuery

Currently, the data is displayed on a page in the following format: AB123 | LHRLAX | J9 I7 C9 D9 A6 | -0655 0910 -------------------------------------------------------- CF1153 | LHRLAX | I7 J7 Z9 T9 V7 | -0910 1305 ---------------- ...

Exploring the power of React Hooks with the useState() function and an array filled

When creating new "Todo" items and modifying the fields, everything works fine. However, my problem arises when trying to retrieve the child data after clicking the "show all objects" button. To better understand my issue, here is a code example: const Co ...

Having trouble removing a DOM element with jQuery?

Hey there, I need your help with a jQuery issue I'm facing. I am currently working on cloning a div element that contains a span with a click event attached to it. The purpose of the click event is to remove the newly cloned section from the DOM. Whil ...

String object causing jQuery selector to malfunction

const newHTML = '<html><head><title>Hello</title><link rel="apple-icon-touch-precomposed" href="image.jpg" /></head><body></body></html>'; alert($(newHTML).find('link[rel="apple-icon-touc ...

Exploring the possibilities of toggling between a personalized CSS design and a Bootstrap CSS layout

Is it possible to implement a dropdown menu on my sample-page using javascript/jquery in order to switch between a custom layout and a bootstrap layout? ...

iPad2 always displays UIWebView in 'portrait' orientation

I have a sophisticated HTML5 website that includes JavaScript. It is displayed in a UIWebView. The JavaScript on the page is supposed to determine whether the iPad is in Portrait or Landscape mode. Unfortunately, I have encountered an issue. Regardless of ...

Refresh collection of texts

I am attempting to update an item within a subarray of a document. The type of the subarray is an array of strings: Dictionary.findOne({ name: req.query.name }, function(err1, data){ if(err1){ logger.error(err1); res.send({ ...

Safari is causing issues with HTML5 Video playback

I have a client with a media-heavy website containing numerous video and audio files. While the videos load perfectly on Chrome, Firefox, and IE, they do not load on Safari for Windows. Here's a snippet of the code: <video controls="controls" type ...

Instructions on adding an activity indicator in a centered box with a loader inside

I'm currently working on integrating an Activity Indicator into my Vue Native App, but I've been facing some issues as it doesn't seem to be displaying the Activity Indicator properly. Here is the code snippet I've tried: <Absolute ...

What is the process for incorporating a compiled JavaScript library into a TypeScript project?

In my Typescript project (ProjectA), I am utilizing several node packages. Additionally, I have a babel project (ProjectB) with a build configuration that supports output for multiple module definition standards such as amd, common.js, and esm. My questio ...

Having trouble with the Wordpress JS CSS combination not functioning properly and unable to determine the cause

I recently set up a page on my WordPress site using the Twenty Seventeen theme. At the top of the page, I created a toolbar for users to easily adjust the font size and background color. Check out the image below for reference: See Image for Bar Here&apo ...

How can I retrieve the URL of the previous page from the history object in all browsers?

Can we retrieve the URL of the previous page from the history object? I've seen references to history.previous, but it appears to be either undefined or protected based on my observations. ...

Utilizing Node.js, delete the author from the database and then use a GET request to display all

Exploring node and express for the first time. I've been working on an example that utilizes GET and POST methods, but now I want to implement DELETE function to delete a book based on its title. Additionally, I need to introduce another GET method to ...

Next.js experiencing development server compile errors and broken page routing in production builds

Howdy everyone! I'm currently working on an app using Next.js. Every time I make a change, the server automatically compiles with the updates, but unfortunately, the pages often fail to render properly. Sometimes it takes several minutes for them to l ...

Managing memory in UIWebView when rendering THREE.js scenes

I am currently working on a game using THREE.js that will be embedded into a UIWebView within an iOS8 app. After analyzing the application in Chrome's developer tools, I have confirmed that there are no memory leaks present. The memory usage reaches ...