LowPro: The essential Prototype companion library to clean up your markup

It’s 2008. There is a short list of things that should never be seen in markup from this point forward:

  • inline event handlers
  • script elements outside of your document’s head

Yes, this includes your Google Analytics tracking scripts. Put those script tags in your document’s head where they belong, and use DOM ready events to fire your tracking.

The key to modern scripting is in your markup. Make it as semantic as you can. Use class names that makes sense, more than one if necessary. Use microformats if you can. Once you do this, you will find id attributes become much less important. I tend to only use them for database objects these days- and even then it can get you into trouble.

There are a lot of third party libraries that expect to be passed an element with an id attribute to function properly. I believe parts of Script.aculo.us are like this. Do not allow these libraries seduce you into adding id attributes where you do not otherwise need them. Behavior-based JavaScript is based around the relationship between elements in the DOM. In most cases, none of the elements need id attributes. From inside behaviors, use DOM traversal methods to find other nodes you need to work with.


The core of LowPro revolves around two functions: Event.addBehavior and Behavior.create. Event.addBehavior can map DOM elements to anonymous functions based on CSS selectors:

   'div.main': function() {
     // 'this' is a reference to a matching DOM node
   'div.secondary,div.tertiary': function() {
     // multiple CSS selectors can be separated by a comma

Event.addBehavior also supports attaching event listeners to DOM elements. Note how the CSS selector has a pseudo-class appended to it:

   'div.main:click': function(event) {
     // 'this' is a reference to a matching DOM node
     // 'event' it the standard Prototype-extended event object

Now when a user clicks on a page element that matches the selector ‘div.main’, the anonymous function is passed the standard Prototype-extended event object and executed, which is cool. 

No more inline <script> tags FTW. I've been using LowPro all this weekend and I've been quite pleased.

1 response
Unobtrusive javascript ftw. This is almost exactly what I have been working on this weekend as well. I was poking around rails 3 code pulling some of the new JS code into old rails 2.3x code (http://github.com/rails/jquery-ujs/blob/master/src/rails.js). No more inline javascript for ajax functions. Event based behavior with callbacks is much more cleaner and easier to maintain.

Btw. What about putting JS right before the tag for slow JS scripts.