The seven rules of unobtrusive JavaScript

Christian Decker wrote this terribly early in the morning:
Christian Heilmann has written a great article about why Unobtrusive JavaScript is the way to go and what the best practices are. I strongly recommend that you head over and read it through. For me the most important points are:
  • You don’t expect JavaScript to be available but make it a nice-to-have rather than a dependency: definitely true as JavaScript should be an enhancement rather than the show itself.
  • You expect other scripts to try to interfere with your functionality and keep the scope of your scripts as secure as possible: true, that’s one of my main criticisms about JavaScript. Not having clean separation seems a big step backwards in evolution.
  • Traversing the DOM is expensive and can be slow, that is why it is a good idea to leave it to a technology that is already in use in browsers. I like to spray hooks on the finished HTML when I need to have simple ways to access DOM-elements. Also I really like caching elements that I searched earlier in variables so I don’t have to search for them again.
  • Using CSS to do manipulation on many elements at once without having to search for the elements (section 3): this is really a great idea, new to me, but I’m sure it’ll come in handy.
  • A really important part of unobtrusive JavaScript is to understand how browsers work (and especially how browsers fail) and what users expect to happen. It is easy to go overboard with JavaScript and create a completely different interface with it. Drag and Drop interfaces, collapsible sections, scrollbars and sliders can all be created with JavaScript, but there is much more to those than just the technical implementation. Agreed! Don’t overdo it, or the users will find it hard to use.
  • The other thing to remember is that you can stop events from being reported to parent elements and you can override the default action HTML elements like links have. However, sometimes this is not a good idea, as browsers apply them for a reason. An example would be links pointing to in-page targets. Allowing for them to be followed makes sure that users can bookmark the state of your script. Oh how many times have I seen <a href=”#” onclick=”…”> to respond to an event. Don’t do it, please.
  • Wrapping functionality in objects provides namespaces and isolation of your code. Better yet: you can define public interfaces! (section 6)
So thank, you very much, Christian, for this article, let’s hope many developers start applying your tips, because they make the world a better place. I know I will :)

Also interesting posts: