Testing for Javascript with Modernizr

When adding a feature that requires Javascript to work, progressive enhancement should be the rule of the day. Always try to think through what happens on the site for a visitor who doesn’t have Javascript available for whatever reason, and provide a simple fallback experience for them.

I use Modernizr to test whether Javascript is available so I can target CSS styles accordingly.

Modernizr’s production feature gives you the option to select only the tests that you need in order to keep its file size as small as possible. Once we download the minified production file of Modernizr, we add it to our site using wp_register_script() and wp_enqueue_script() (follow the links to the WordPress Codex for details). We add something like the following to the functions.php file in our WordPress theme folder.

wp_register_script( 'my-modernizr', get_stylesheet_directory_uri() . '/library/js/libs/modernizr.custom.min.js', array(), '2.5.3', false );
wp_enqueue_script( 'my-modernizr' );

In our header.php template, we give the <html> element a class of “no-js”, which Modernizr changes to “js” if Javascript is available.

Then we style the javascript-only view. Since I have javascript in my own browser and don’t want to be bothered to turn it off, I will temporarily prefix the styles for my no-Javascript fallback using the “js” class, like so:

.js .slides {
  margin-top: 1em;

Once I’m happy with the result and feel like users without Javascript will have a decent, usable experience, I add the “no-” to set those styles aside for our no-js friends:

.no-js .slides {
  margin-top: 1em;