Creating gracefully degrading javascript and enabling progressive enhancement

Creating gracefully degrading Javascript and CSS is pretty simple these days. I’m sure this has been written about a million times over as well. However, I thought it would be worthwhile to share how I do it as well. Mainly, because in addition to AJAX and effects I use Javascript as a way of enabling different CSS selectors for elements. Doing this is actually quite simple, and allows you to easily alter the presentation of dynamic elements when Javascript is not available. I use this little snippet (written with Mootools) to accomplish this.

Show Plain Text
  1. window.addEvent('domready', function() {
  2.     $$('html')[0].addClass('js');
  3. });

This adds the class js to the <html> element. Making it very easy to make javascript enabled only CSS. A selector of #content .popup becomes html.js #content .popup. Also these Javascript enabled rules have greater specificity giving you greater flexibility as to where in the CSS source they can be placed.


An other way would be to load a javascript-only css file by putting a
<script language="javascript" type="text/javascript">/* <![CDATA[ */ document.write('<link rel="stylesheet" type="text/css" href="javascript.css" media="screen, projection" />'); /* ]]> */</script>

And putting this after your regular stylesheet, you just have to override your rules with rules of the same name.

Doing so you will reduce the filesize of your original css file, removing commands that won’t be used.
But you’ll have an extra server hit for those people with javascript…

I did not say my way was better, just an alternative ;)

anonymous user on 9/21/08

Pixelastic: That is another viable option. I don’t think this is a subject where there is one ‘right’ option. There are many viable and good options each with their own benefits.

mark story on 9/23/08

Comments are not open at this time.