javascripthtmlcssfouc

Preventing FOUC when calling CSS through JavaScript


I have a webpage which I have altered from a template. I am suffering from FOUC (Flash of Unstyled Content).

I have tried a solution from here: https://docs.google.com/presentation/d/1jt_VQC5LDF-e9j8Wtxu4KZPa8ItlmYmntGy5tdcbGOY/present?slide=id.p

but could not get it to work. Here is a main part of my head, the scripts are calling my CSS in (I think!).

<head>
    <!--[if lte IE 8]><script src="js/html5shiv.js"></script><![endif]-->
    <script src="js/jquery.min.js"></script>
    <script src="js/skel.min.js"></script>
    <script src="js/skel-layers.min.js"></script>
    <script src="js/init.js"></script>
</head>

<body id="top">
            bunch of stuff to hide until style has loaded. 
</body>

The idea of this solution is to pause the load of the content until the CSS has loaded, but I am not sure whether it will work when calling with a java script.

Here is what I tried:

<head>

    <style type="text/css">
        #fouc { display: none; }
    </style>

    <script type="text/javascript">
        document.documentElement.className = 'js';
    </script>

    <!--[if lte IE 8]><script src="js/html5shiv.js"></script><![endif]-->
    <script src="js/jquery.min.js"></script>
    <script src="js/skel.min.js"></script>
    <script src="js/skel-layers.min.js"></script>
    <script src="js/init.js"></script>

</head>

<body id="top">

    <div id="fouc">
            bunch of stuff to hide until style has loaded. 
    </div>

    <script type="text/javascript">
        document.getElementById("fouc").style.display="block";
    </script>

</body>

This did not work. Can anyone suggest a way to stop the FOUC in this scenario?

Thank you for your patience, I appreciate the help,

J


Solution

  • This was my solution:

        <script src="js/jquery.min.js"></script>
        <script src="js/skel.min.js"></script>
        <script src="js/skel-layers.min.js"></script>
        <script src="js/init.js"></script>
    
         <style type="text/css">
           .no-fouc {display: none;}
         </style>
    
        <script type="text/javascript">
          document.documentElement.className = 'no-fouc';
         $(window).on("load", function() {
            $('.no-fouc').removeClass('no-fouc');
         });    
        </script>
    

    This whole thing went into the <head> with no changes to the <body>.

    Which rather than using classes and id's in the body section, uses $(window).on("load", function() to only load the page once the content is loaded. be sure to load jQuery before the script block.