- Published on
Fixing flash of unstyled content
- Author
- Illia Vasylevskyi
I've been working on my blog website, deployed it, everything was working but I've noticed warning in Firefox about flash of unstyled content.
This problem is well known - Flash of unstyled content
To fix this we will hide everything and show when page is loaded.
To hide we will change body visibility:
<body style="visibility: hidden;">
<!-- Our main content -->
</body>
Back in the days we were using JQuery document.ready, but now we can easily do it with JS:
const domReady = (callback) => {
document.addEventListener('DOMContentLoaded', callback)
}
domReady(() => {
// Display body when DOM is loaded
document.body.style.visibility = 'visible';
// ... other inits
})
So now everything should work right? Reloading the page and we see that nothing changed in Firefox. To fix this we need to add small "hack"
<body style="visibility: hidden;">
<script>0</script>
<!-- Our main content -->
</body>
Reload page, and now everything works.
But what will be if someone don't have JavaScript enabled in browser (in 2024 he most likely will not be able to use any site =) ) Still let's fix it:
<noscript>
<style>body { visibility: visible !important; }</style>
</noscript>
Now we are ready to use our site without FOUC!