Avoiding the FOUC

For several years I’ve used Paul Irish’s technique for avoiding the FOUC caused by JavaScript kicking in. I’ve recently changed to a slightly improved version.

The code in Paul’s original article is:

<html class="no-js">

A small typo on the html element had me debugging working JavaScript for about ten minutes recently, so I’ve switched to something a tiny bit more robust:

<html class="no-js">
<script>(function(H){H.className=H.className.replace(/\bno-js\b/,'')+' js'})(document.documentElement)</script>

This change prevents the active class (.js) relying on the presence of the inactive class (.no-js) to be applied. Something similar is used in Modernizr, so I’m far from the first person to think of this.

If you want to save yourself an extra few bytes, then you might want to consider:

<html class="no-js">
<script>(function(H,c){H[c]=H[c].replace(/\bno-js\b/,'')+' js'})(document.documentElement,'className')</script>

By Peter Wilson

Peter has worked on the web for twenty years on everything from table based layouts in the 90s to enterprise grade CMS development. Peter’s a big fan of musical theatre and often encourages his industry colleagues to join him for a show or two in New York or in the West End.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.