While at An Event Apart Boston, Jeremy Keith delivered the best lecture of the conference, about progressive enhancement. One slide caught my attention the most. It was about adding a class to the body if JavaScript was available. Here is his code example using jQuery:
Keith's Example using jQuery:
jQuery(function($) { $('body').addClass('hasJS'); });CSS
.hasJS .module { display: none; }
Why add a class if JavaScript is enabled?
Although the majority of desktop users have JavaScript enabled, mobile is one of the most used platforms to surf the web. Some mobile browsers don't support JavaScript. Keep in mind that search engines don't run JavaScript, so NEVER add important content using JavaScript.
My current project at work requires the content to be rendered for both enabled and disabled JavaScript browsers. I did a bit of research and found that most websites/solutions add the hasJS class to the body after the

You might be asking why add the class to the HTML element? I think it makes more sense because the BODY is the beginning of the content. This means that everything after the body is "visible" to the user and blocking the content with a script tag isn't a good optimization practice. Here is the code to add the hasJS class to the body:
hasJS Script Block
<script type="text/javascript"> document.getElementsByTagName('html')[0].className = 'hasJS'; </script>
NOTE: If you already have more classes on the HTML element, use document.getElementsByTagName('html')[0].className += ' hasJS'; instead.
DemoBrowser Support
- Firefox
- Safari
- Chrome
- Opera
- Internet Explore 7 & 8
- Internet Explore 6
Comments
leave a commentHopefully, people already buy into the JS versus no JS experience. I think the argument is stronger than simply ‘if JS is available or not.’ On some mobile platforms, engineers may choose to serve the non-JS experience so as to get maximum accessibility.
I would expect that popular UI patterns such as Yahoo Patterns would build in a JS-less version of each.
We’re building our modules/widgets for our company so that each one can work in a full page (standalone) mode. I’ll try to put out a follow up to your post if we ever pull it off.
We still should immediately pick the low hanging fruit: accordions should be fully opened when hasJS === false, tabbed controls should render stacked vertically, etc.
I’m with you Rodio!
-tateman
This is a useful idea, it’s simple yet displays quite effectively. Thanks for posting.