Replace Noscript with CSS

Since CSS was added for determining what and how the content of the web page is to be displayed the <noscript> tag has been completely unnecessary. We can replace it in every possible instance with a single line of JavaScript and one line of CSS. This also has the advantage that it can be applied to inline content and not only to block content the way noscript had to be applied. In addition it can make other distinctions between the JavaScript enabled content and the JavaScript disabled content that are not easily done using noscript.

First you need to add the single line of JavaScript to the head of your page (this is only instance I have come across where JavaScript needs to go in the head where it relates to the current page rather than redirecting to a different page).

document.getElementsByTagName('html')[0].class += ' js';

With this line of code in place you can now simply add class="nojs" to all of your noscript content instead of having to use the noscript tag. You then add a single line of CSS to make all of them disappear when JavaScript is enabled.

.js .nojs {display:hidden;}

We can even make use of this to apply any styling we like that needs to distinguish whether JavaScript is enabled or not. For example the following two CSS commands would result in the text in the page displaying in blue if JavaScript is not enabled and in red if it is enabled.

p {color:#00f;}
.js p {color:#f00;}

You can't do that using noscript unless you wrap the entire content inside the noscript tag and regenerate it all over again from the JavaScript.

Note that the modernisr script works on this principle and goes further with setting classes on the html tag to identify many things that browsers may or may not support.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow