The rules of unobtrusive JavaScript

One of the most important things to keep in mind when writing JavaScript for the Web is to make it unobtrusive, since You cannot rely on JavaScript being available.

Sadly, there are many developers who do not seem to spend any energy at all on considering how to do that. Instead they choose to blindly forge ahead and assume that everybody who comes visiting will have full support for JavaScript and use a mouse.

Luckily there are a number of web developers who advocate unobtrusive JavaScript. One of the most noticeable ones is Chris Heilmann, who talks a lot about it in his book Beginning JavaScript with DOM Scripting and Ajax. Recently Chris held a workshop on the subject, and while preparing his materials for the workshop he defined The seven rules of Unobtrusive JavaScript:

  1. Do not make any assumptions: Don't expect JavaScript to be available, and don't expect the intended markup to be there.
  2. Find your hooks and relationships: Examine the HTML you are working with to find the best way of letting your script interact with it.
  3. Leave traversing to the experts: When possible, let CSS take care of finding the element you want to change.
  4. Understand browsers and users: Don't deviate too far from the way browsers work and how users expect them to work.
  5. Understand Events: Learn how event handling helps you separate your JavaScript from your HTML.
  6. Play well with others: Make sure your script does not interfere with others, and make it hard for other scripts to interfere with yours.
  7. Work for the next developer: Make maintenance easier by writing logical code with clear variable and function names and commenting where necessary.

It's all excellent advice that goes beyond unobtrusive scripting and into the realm of general best practices.

The JavaScript-focused blog Ajaxian asked Chris a few questions about unobtrusive JavaScript and links to his article in Unobtrusive JavaScript - Rules to work by. The comments on that post contain some examples of the careless attitude among many developers that I mentioned earlier. It's fascinating to see people actively argue against unobtrusive JavaScript.

I guess no matter which part of web development you look at there will always be people who couldn't care less about craftsmanship and quality, and are always on the lookout for shortcuts and ways to shut out minorities.

Posted on November 27, 2007 in JavaScript, Accessibility