Monthly Archives: May 2012

Getting around the flicker of JavaScript modifying the DOM while the page is loading

When building things with progressive enhancement, I often want the page styled a certain way when JavaScript is on vs off. When you use $(document).ready() in order to modify your page, you may end up watching the page modify before your very eyes, and if you’re like me, wish you could find a way around it.

For instance, I might have portions of a form hidden by default unless the user clicks an option to expand it. My old method was to show it all by default, then using $(document).ready(), hide those options. The problem is that I would see a flicker as elements start appearing then disappearing on my screen.

Now I use this method:

<body class="nojs">
    <script>
      var bodyEl = document.getElementsByTagName('body');
      bodyEl[0].className = bodyEl[0].className.split('nojs').join(' jsEnabled ');
    </script>
    ...
</body>

So by default, my page has a nojs class. And a script runs immediately after to remove that class, and to add in a ‘jsEnabled’ class in its place. I can then do things in my stylesheet like this:

.conditionalContent { display:none; } // what I really want to happen
.nojs .conditionalContent { display:block; } // in case JS is disabled

This accomplishes the same thing as I was trying to do above (keep an element hidden by default if JavaScript is disabled, but show it by default if JavaScript is disabled) but without the flicker.

And then you also have an option to make use of .jsEnabled class in the stylesheet as well.

If you happen to have jQuery pulled into your site in your <head>, you can use this instead:

<body class="nojs">
    <script>
      $('body').removeClass('nojs').addClass('jsEnabled');
    </script>
    ...
</body>

If anyone’s discovered other methods of getting around this type of issue (like using Modernizr, or something else), I’d love to hear about it.