How to stop FOUC when using css loaded by webpack

后端 未结 3 751
盖世英雄少女心
盖世英雄少女心 2020-12-29 22:11

I am getting FOUC when loading css inside of my entry point when using webpack. If I remove my css from being loaded by webpack and just include it in my html file as a norm

相关标签:
3条回答
  • 2020-12-29 22:30

    A bit late to the party, but here's how I do it.

    While I recognize the merits of extract-text-plugin, it's plagued by a rebuild bug that messes up css order, and is a pain to set up. And setting timeouts in js is not something anyone should be doing (it's ugly and is not guaranteed 100% to prevent fouc)...

    So my index.html is:

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8"/>
        <style>
          #app { display: none }
        </style>
        <title></title>
      </head>
      <body>
        <div id="app"></div>
        <script src="scripts/bundle.js"></script>
      </body>
    </html>
    

    Then, in client.js at the very end I add:

    include "./unhide.css";
    

    ...and unhide.css contains a single line:

    #app { display: block }
    

    Voila, you see nothing until the whole app is loaded.

    0 讨论(0)
  • 2020-12-29 22:42

    ExtractTextWebpackPlugin will allow you to output your CSS as a separate file rather than having it embedded in your JS bundle. You can then include this file in your HTML, which as you said, prevents the flash of unstyled content.

    I'd recommend only using this in production environments, as it stops hot-loading from working and makes your compile take longer. I have my webpack.config.js set up to only apply the plugin when process.env.NODE_ENV === "production"; you still get the FOUC when you're doing a development build/running the dev server, but I feel like this is a fair trade off.

    For more information on how to set this up, take a look at SurviveJS's guide.


    Update: As noted in the comments, ExtractTextWebpackPlugin has now been superceded by mini-css-extract-plugin - you should use that instead.

    0 讨论(0)
  • 2020-12-29 22:44

    It's janky, but I wrap ReactDom.render() in a setTimeout() in my root index.js file.

    setTimeout(ReactDOM.render(...), 0)

    0 讨论(0)
提交回复
热议问题