JavaScript Style Sheets

One of the privileges I have experienced in my professional life is having worked with Jeremy Keith of Clearleft. I learned a lot from the author and web developer from our interactions and by studying his code.

Jeremy is a fan of graceful degradation and ensures that a site will function just fine without JavaScript browser support. However, instead of mingling JS and non-JS styles together, he employs a particularly clever technique. He puts the standard styles in the standard CSS file. But just as his sites provide print and mobile stylesheets for printers and mobile devices, he also provides one for JS-enabled browsers. This has two nice side-effects: (1) better CSS organization and (2) CSS that is applied immediately, not after JS has had an effect on the DOM.

One example is a thumbnails carousel he designed. If the browser does not have JS support, the thumbnails are arranged in a grid. If the client does support JS, he wraps-up the thumbnails in a single row inside a horizontally-scrolling carousel, so they can be browsed left to right. The carousel presentation of the thumbnails requires a different set of CSS rules, which override the vanilla styles.

Here’s how he pulls off the wiring-up of a JavaScript CSS style sheet:

  <script type="text/javascript">document.write('<link rel="stylesheet" href="/stylesheets/javascript.css" media="screen,projection">');</script>

Any site I’m involved in will be following suit.

Thanks, Jeremy!

Advertisements

One thought on “JavaScript Style Sheets

  1. Tamara B.

    Ian,
    Hope all is well with you. I check in with your website every few months to see what is new, you always seem to have something thought provoking and this gem was no excpetion.

    It feels like in general most applications stop at ‘happy path’ design and test. Assuming no resources will be busy, a powerful client connected over a super fast network with all the proper plugins. Would we accept a car that only works on flat, dry roads? We would all do better allow for some robustness in our solutions and your example about javascript is a great place to start.

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s