Fix FOUC ‘flash of unstyled content’ on WordPress

FOUC aka ‘flash of unstyled content’ is a bit of a pain after a layout has been put together but does not load without that flash of odd content jumbled up on load.

Using a snippet of jQuery by adding and later removing a CSS class of hidden to the html element but then showing it all when the document is ready is a good way to combat FOUC.

add_action('wp_head', 'fouc_protect_against');
/**
 * Combat FOUC in WordPress
 * @link https://stackoverflow.com/questions/3221561/eliminate-flash-of-unstyled-content
 */
function fouc_protect_against () {
    ?>
        <style type="text/css">
            .hidden {display:none;}
        </style>
        <script type="text/javascript">
         jQuery('html').addClass('hidden');
	            
	 jQuery(document).ready(function($) {		            
	    $('html').removeClass('hidden');	            
	 });  
        </script>
    <?php

}

Add in your functions.php

4 Comments

  1. Jegkiralyfi on August 21, 2019 at 5:32 am

    Works perfectly! Thanks for that!

  2. jim on April 12, 2019 at 3:09 am

    Thanks, it works now!

  3. jim on April 11, 2019 at 7:47 pm

    I tried this but it made the whole page white and never loaded the content, even after waiting a while.

    • Neil Gowran on April 12, 2019 at 3:00 am

      I had an error in the code, have updated it now.

Leave a Comment