plasticwrapper

design and development for the web


Javascript Styles

Here's a quick tip for anyone trying to maintain graceful degradation of javascript. Keep all your javascript-dependent styles in a separate stylesheet and use javascript to load those styles immediately in the head of the document.

A quick and dirty example:

<html>
  <head>
    <script type='text/javascript'>
      document.write("<link rel='stylesheet' type='text/css' media='screen' href='js.css'>");
    </script>
  </head>
  <body>
    ...
  </body>
<html>

View the demo for a better implementation.

Why is this useful?

While developing a web application that contains javascript enhancements that degrade gracefully, it is often beneficial to have separate styles to help handle that degradation.

What problems does this solve? How does this benefit the user experience?

  • Hide page elements before onload is called
  • User doesn't get "flashes" of page elements that suddenly go away.
  • Style content in a way that makes more sense for non-javascript user-agents.

Before loading the body of a page, it is possible to detect whether the user-agent supports javascript.  This allows greater flexibility with styles for javascript enhancements.

An Unobtrusive Example Using Tabs

Let there be a page with three separate tabs of content.  Clicking one of the tabs will switch between content without loading a new page.  If javascript is disabled, the user should not see three tabs.  Instead, the user should see 3 "normal sections of content" running down the page.

View the demo.

(Disclaimer: In this demo, the code for invoking the tabs is not what I would call beautiful.)

Tags: , , , , , ,

Categories

Recommended Materials