How to fix FOUC in react isomorphic application

How to fix FOUC in react?

What is FOUC ?

FOUC or Flash of Un-Styled Content is rendering of webpage content to a user before all the styles are applied to it. I use boilerplate by erikras for my react isomorphic applications and I totally adore this one, Neat and Nice!

It follows the best practices and is super easy to understand.However, FOUC still remains an issue to deal with a lot of times and that’s what got me to write this blog post.

This is what a webpage with FOUC may look like:

FOUC in react

Techniques to fix FOUC in react ( Flash of unstyled content) :

1. Hiding contents of the page until all javascript and CSS has been downloaded:

While this technique works, I consider it a no go, especially when I am working with React. The only reason that I like to use React in my projects is fast rendering with server-side support.

2. Preventing FOUC with Webpack: Webpack uses JS to inject styles, so you may get FOUC in react with client-rendered webpage and that happened even if I was loading my styles before rendering the web components.

With Webpack, it indeed is a simple fix to prevent FOUC in react with your server-side rendered react application.

Use Extract text Webpack Plugin for loading scss, less and css.

To add the loaders in your Webpack config file, use the following piece of code:

{        test: /\.scss$/,        loader: ExtractTextPlugin.extract(['css-loader', 'sass-loader'])      },      { test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader')},

What Extract Text Plugin does is it moves all the required styles in entry chunks into a separate single CSS file. So your styles are no longer inlined into the JS bundle, but separate in a CSS bundle file which gets loaded into the head part of your HTML to prevent FOUC.

This is how I load it in my head part:

Note: I use ExtractTextPlugin for my production builds only. However, I managed to fix FOUC for development webpack config as well without using webpack ExtractTextPlugin.

Here’s the configuration in my development config file for webpack and it works well without any FOUC/flash of unstyled content for my development build

{ test: /\.css$/, loader: 'style-loader!css-loader'},      { test: /\.less$/, loader: 'style!css?importLoaders=2&sourceMap!autoprefixer?browsers=last 2 version!less?outputStyle=expanded&sourceMap' },      { test: /\.scss$/, loader: 'style!css?importLoaders=2&sourceMap&!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap' }

I hope that helps! ๐Ÿ™‚

P.S: Internet is a successfully thriving community from generous contributions of people from across the globe. You can help it thrive too. Please contribute. As a reader, you can be contributing with your valuable feedback.
Please drop by a comment or Share to let people know you were here. ๐Ÿ™‚ ๐Ÿ™‚

Leave a Reply

Your email address will not be published. Required fields are marked *