Struggling to remove FOUC (Flash Of Unstyled Conte

2019-07-14 00:24发布

I have bundled my app code using webpack 2. Used require statement on my main module to embed an SCSS file.

require('./styles/styles.scss');

While things work fine in all browsers, there is a FOUC (Flash Of Unstyled Content) visible when loading the application.

Is it the way all webpack modules load since CSS files are injected dynamically to header or am I doing something wrong in webpack config?

Here is a snippet of webpack config - loader section:

{
    test: /\.scss$/,
    loaders: [ 'style-loader', 'css-loader?sourceMap', 'sass-loader?sourceMap' ]
}

Albeit this isn't causing any side effects but would be better if avoided.

Thanks.

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-07-14 00:44

Right now your styles are baked into the JS files. In your case, the browser takes a while to parse the javascript and only after processing it can apply the styles to the page. That is causing the FOUC.

To cope with this problem ExtractTextPlugin was developed. Basically what it does is it takes out the css specified and puts it in a separate css file. A basic configuration would look like:

const plugin = new ExtractTextPlugin({
  filename: '[name].[contenthash:8].css',
});

module: {
      rules: [ {
          test: /\.css$/,
          use: plugin.extract({
            use: 'css-loader',
            fallback: 'style-loader',
          })
       }]
},
plugins: [ plugin ]

Then you must attach the generated file to your HTML page if you're not using html-webpack-plugin. By linking generated file in section you will get rid of FOUC.

查看更多
登录 后发表回答