The JavaScript Way

The real world case for unobtrusive JavaScript

Unobtrusive JavaScript (UJS) has gained mainstream acceptance. Except for a few holdouts, the collective conscience of web developers has changed from thinking inline JavaScript is good enough to accepting that UJS is the modern and right way to add behaviour to web pages. But this is not the same thing as really understanding how JavaScript relates to modern web development; I believe there’s a word for this kind of collective behaviour.

I want to explain the real world, pragmatic and practical reasons for unobtrusive JavaScript. Actually, I think the word unobtrusive is misleading because unobtrusiveness is just a side effect of what I will call structured JavaScript. It is not purity for purity’s sake that should drive you towards a cleaner, more structured, more reusable and more scalable way to program JavaScript, but the benefits inherent in these qualities, including keeping your sanity when dealing with less-than-trivial functionality.

First, let’s examine the weaknesses of unstructured or obtrusive JavaScript:

The basic tenets of good programming apply to JavaScript just as much as they do to Ruby or Java programming. Modularity, proper structure, reusability and encapsulation provide exactly the same benefits for JavaScript programming as they do for other languages and “obtrusive” JavaScript breaks all of these practises. Inline JavaScript is to structured JavaScript what PHP is to Ruby on Rails: Its simplicity only works in its favour for very simple applications. JavaScript is a rebellious teenager in need of structure and discipline; you’re the parent who must send it to boarding school.

So what are these benefits I talk about? They’re basically the opposite of the weaknesses of not following best practises:

Contrary to what a lot of people think, writing structured JavaScript is not more work than using inline code. There is a small penalty at the very beginning where the overhead of separating behaviour from content is noticeable, but at a certain point the relation reverses to mean that inline code is more work, and that threshold is very low.

JavaScript is a real programming language. Stop using it like it’s PHP and start using it to your own benefit.

Posted by Tore Darell on Mar 14 2010

Comments

Log in to comment.