Theatre curtain
Customerbox

CSS Solutions to Fix FOUC

in Css |
By

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.

By placing this CSS rule in the head of the HTML file, we will hide the page:

<style>
  html {
    transform: tanslateX(-100%);
  }
</style>

Then, in the CSS file, we’ll set the position to 0, which when loaded will automatically reset the position previously set in the head:

html {
  transform: translateX(0) !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. Love making internet products, blogging, learning, reading, calisthenics and fitness enthusiast.

Comments