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">
<head>
<script>(function(H){H.className=H.className.replace(/\bno-js\b/,'js')})(document.documentElement)</script>

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">
<head>
<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">
<head>
<script>(function(H,c){H[c]=H[c].replace(/\bno-js\b/,'')+' js'})(document.documentElement,'className')</script>

Comments

Leave a Reply

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.