Please Support - Ride for the child

I’ve learnt something this week that I’m going to briefly write about. It’s basically about how I would style something that has to function both with and without JS functionality. A shout out to Colin from McCann who helped me with this.

I used to add a class to something like this…

html class="no-js"
body class="no-js"

Then I would simply remove the class when it reads the Javascript/jQuery

$('html').removeClass('no-js');

$('body').removeClass('no-js');

There are a couple of reasons as to why I am now against this approach.

  • Javascript should be loaded in the footer of a page, so all the CSS is read first (including the no-js styles) and then the class removed once the browser reads the JS. The could cause the page to ‘flicker’ between the two sets of styles. Something we really need to avoid.
  • After learning to code mobile first. It is only right that I should embrace a progressive enhancement approach for JS too. In other words my no-js styles come as standard and my ‘advanced’ JS styles come after. (Only the advanced styles are declared, no-js won’t exist)
  • We should use JS as opposed to jQuery as we would have to load the library in first.
  • We should apply the advanced class to the HTML tag as it is the first element that is rendered.

So now my HTML tag doesn’t include a no-js, or advanced class. It is simply.

html lang="en"

The I use the following code snippet to add an ‘advanced’ class onto my html element if JS is enabled.

document.documentElement.className = 'advanced';

And style something like this.

.movingElement {display: block;}

/* The following is hidden initially then uses JS to add move functionality */
.advanced .movingElement {display: none;}

The are loads of other ways this can be done including using modernizr, but this is the approach I am now using. It has been added to my Base template if you want to check a working example out.