Easier Development with Unobtrusive JavaScript

Unobtrusive JavaScript is a poorly defined umbrella term. It's generally agreed to encompass:

  • Separating behavior from content, much like separating style from content.
  • Avoiding browser specific javascript bugs.
  • Supporting browsers without javascript.

My definition is a little more simple. Make your pages functional in plain HTML.

Now, there is a good amount of grumbling from the peanut gallery on this issue. Here are some common objections, and rebuttals.

The year is 2009. Everyone has javascript. This is a waste of time.

Actually, 5% of users don't have javascript. You can break these users down into the following groups:

  • Really old browsers
  • Users with disabilities (think screen-readers)
  • NoScript users. XSS is now the most exploited attack vector. Knowledgeable users may choose to opt-out.
  • Googlebot. If you want Google to index your site (hint: yes), then your content needs to be available with javascript disabled.
I don't know how. It seems hard.

It's really not. It's just taking separation to the next level. You're already separating HTML from CSS (you ARE doing that, right?), now just pull the javascript out, too. Ie, instead of this:

<a href="javascript: nextPage();" style="font-weight: bold; color: red;">Next Page</a>

Do this (nod to A List Apart):

<a href="thisPage.php?page=2">Next Page</a>
A { font-weight: bold; color: red; }
// using jQuery
$("a:contains(Next Page)").click(function() {
 return false;

You've allowed for graceful degradation without javascript; the user will simply be redirected to the next page. You have allowed for enhanced functionality with the Ajax call if javascript is available. Plus, you've separated your style, content and behavior. How do you reduce code duplication? Simply have nextPage() make an Ajax call to the href of the A tag (no need to specify the URL again), and get the new content. Then merge the new content into the existing page. More on this next time.

I can't implement this feature without javascript. It's not possible.

Typically these are UI tasks. For example, a Google suggest auto-complete. That drop down is flatly impossible without javascript, yes. But Google itself works just fine without this feature. This is graceful degradation.

Won't I end up writing two versions of the site, one with javascript, and one without? That's a lot of extra code.

Not if you're smart about it. This is where Unobtrusive JavaScript comes in. Writing Ajax apps can actually be easier with Unobtrusive JavaScript. Tune in next time for a practical discussion.