I notice that in a lot of template engines, in the HTML5 Boilerplate, in various frameworks and in plain php sites there is the no-js
class added onto the <HTML>
tag.
Why is this done? Is there some sort of default browser behavior that reacts to this class? Why include it always? Does that not render the class itself obsolete, if there is no no-"no-js" case and html can be addressed directly?
Here is an example from the HTML5 Boilerplate index.html:
<!--[if lt IE 7 ]> <html lang="en" class="no-js ie6"> <![endif]-->
<!--[if IE 7 ]> <html lang="en" class="no-js ie7"> <![endif]-->
<!--[if IE 8 ]> <html lang="en" class="no-js ie8"> <![endif]-->
<!--[if IE 9 ]> <html lang="en" class="no-js ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html lang="en" class="no-js"> <!--<![endif]-->
As you can see, the <html>
element will always have this class.
Can someone explain why this is done so often?
When Modernizr runs, it removes the "no-js" class and replaces it with "js". This is a way to apply different CSS rules depending on whether or not Javascript support is enabled.
See Modernizer's source code.
Look at the source code in Modernizer, this section:
So basically it search for classPrefix +
no-js
class and replace it with classPrefix +js
.And the use of that, is styling differently if JavaScript not running in the browser.
The
no-js
class gets removed by a javascript script, so you can modify/display/hide things using css if js is disabled.Modernizr.js will remove the
no-js
class.This allows you to make CSS rules for
.no-js something
to apply them only if Javascript is disabled.The
no-js
class is used by the Modernizr feature detection library. When Modernizr loads, it replacesno-js
withjs
. If JavaScript is disabled, the class remains. This allows you to write CSS which easily targets either condition.From Modernizrs' Anotated Source (no longer maintained):
Here is a blog post by Paul Irish describing this approach: http://www.paulirish.com/2009/avoiding-the-fouc-v3/
I like to do this same thing, but without Modernizr. I put the following
<script>
in the<head>
to change the class tojs
if JavaScript is enabled. I prefer to use.replace("no-js","js")
over the regex version because its a bit less cryptic and suits my needs.Prior to this technique, I would generally just apply js-dependant styles directly with JavaScript. For example:
With the
no-js
trick, this can Now be done withcss
:This is preferable because:
This is not only applicable in Modernizer. I see some site implement like below to check whether it has javascript support or not.
If javascript support is there, then it will remove
no-js
class. Otherwiseno-js
will remain in the body tag. Then they control the styles in the css when no javascript support.