DOM flickering occurs when you hide elements using JavaScript and there’s a noticeable delay between the page being loaded and the element actually hiding. This usually happens because you’re handling the removal upon the onload event; this is generally a bad idea – this event will not fire until everything has loaded, including images!

It’s considered better practice to use one of the various domReady abstractions available. Unfortunately, this won’t always work either, especially with large DOM structures! One method I’ve been using recently to avoid the flicker is to add a class to the body element as soon as it exists, thereby making it possible to affect the styling of these elements before they even exist within the DOM! An example:

<!-- SIMPLIFIED -->
<html>
    <head>
        <style type="text/css">
            body.js .nojs { display: none; }
        </style>
    </head>
    <body>
 
        <!-- BODY element exists! -->
        <script>
            document.body.className += ' js';
        </script>
 
        <div class="nojs">
            ... No flicker!
        </div>
 
    </body>
</html>

Or, more cleanly:

<!-- SIMPLIFIED -->
<html>
    <head>
        <style type="text/css">
            html.js .nojs { display: none; }
        </style>
        <script>
            // Add class to <html> element
            document.documentElement.className += ' js';
        </script>
    </head>
    <body>
 
        <div class="nojs">
            ... No flicker!
        </div>
 
    </body>
</html>

How do you solve the “flicker” problem?

Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!