Fixing Flash of Unstyled Content (FOUC) in Jekyll Sites
The Problem: Flash of Unstyled Content
If you’ve ever loaded a Jekyll site and noticed a brief flicker where unstyled HTML content appears before your CSS kicks in, you’ve experienced what web developers call a “Flash of Unstyled Content” or FOUC. This jarring visual glitch happens when your browser renders HTML content before the associated stylesheets have finished loading.
For Jekyll sites, this issue is particularly common because of how the platform processes and serves content. The browser starts rendering the HTML document as soon as it receives it, but external stylesheets might take a bit longer to download and parse.
A Simple but Effective Solution
After experiencing this issue on my own Jekyll site, I implemented a minimal fix that completely eliminates the FOUC. The solution involves just a few lines of CSS and JavaScript and works by:
- Initially hiding the entire page content
- Revealing the content only after all resources (including CSS) have loaded
Here’s how I did it:
Step 1: Modify custom-head.html
First, I added the following code to my _includes/custom-head.html
file:
<!-- Fix for Flash of Unstyled Content (FOUC) -->
<style>
.no-fouc {
visibility: hidden;
}
</style>
<script>
document.documentElement.className = 'no-fouc';
window.addEventListener('load', function() {
document.documentElement.className = '';
});
</script>
This creates a CSS class that hides elements and sets up a JavaScript event listener that will remove this class once everything has loaded.
Step 2: Apply the class to the HTML element
Then, I updated my _layouts/base.html
file to add the class to the root HTML element:
<!DOCTYPE html>
<html lang="en" class="no-fouc">
How It Works
The solution works through these key mechanisms:
- The
.no-fouc
CSS class setsvisibility: hidden
on any element it’s applied to - We apply this class to the root
<html>
element through JavaScript immediately - The
load
event listener waits until all page resources (HTML, CSS, JS, images, etc.) have finished loading - Once everything is loaded, we remove the class, making the page visible
Benefits of This Approach
This solution has several advantages:
- Minimal code: Just a few lines of CSS and JavaScript
- No dependencies: Doesn’t require jQuery or other libraries
- Preserves page structure: Unlike some solutions that completely hide the body, this approach maintains the document flow, preventing layout shifts
- Works with Jekyll’s default setup: No need to modify your build process
Testing Your Fix
To confirm the fix works:
- Open your site in a browser with the network throttled (in Chrome DevTools, use the Network tab to simulate a slow connection)
- Refresh the page
- You should see the page appear fully styled, with no interim unstyled content
This simple solution provides a much better user experience by ensuring visitors only see your site when it’s fully styled and ready for presentation.