CSS Solutions to Fix FOUC

I've finally decided to fix a bug I've been seeing for a long time, which I always would leave for later as it was a minor bug. This bug is called FOUC or Flash of Unpainted Content, so I decided to share with you these 2 solutions to this simple problem.

Theatre curtain
Customerbox

Today, I’ve finally decided to fix a bug I’ve been seeing for a long time, which I always would leave for later as it was a minor bug. This bug is called FOUC or Flash of Unpainted Content, so I decided to share with you these 2 solutions to this simple problem.

The problem is relatively simple, avoid showing unstyled HTML elements scattered through the page while the CSS file is being loaded.

There are 2 solutions to this problem, a longer one and a quicker one, you decide which one works best for you.

Solution 1:

This solution is more complicated to implement but much better. The idea is to extract critical CSS from the file and inline in the head. By saying critical I mean all the styles of the above-the-fold content visible on the page load.

This technique will make the page instantly interactable without showing unstyled elements, while the rest of the CSS file will load in async without blocking.

There are a few NPM plugins to achieve this without going manually over files, like Critical, CriticalCSS

Solution 2:

A quicker solution would be hiding the HTML element while the CSS file is being loaded. This not-so-great solution would make the time-to-interactivity longer, but it will avoid showing unstyled elements and CLS.

First we will set the visibility rule to hidden in the head of the HTML file, this will hide the page while the CSS file is being downloaded:

<head>
  ...
  <style>
    html {
      visibility: hidden;
    }
  </style>
</head>

Then, in the CSS file, we’ll set the visibility to visible, which when loaded will automatically show the page already styled.

html {
  visibility: visible !important;
}

Conclusion

Depending on the structure, urgency, and importance of the project you can always consider one of the two solutions.

Author

Bojan Vidanovic is a computer programmer, specialized in front-end web development. Creator of Lynky and Dev & Gear. Love making internet products, blogging, learning, reading, calisthenics and fitness enthusiast.

Read also