Obtrusive Javascript and Rails

June 30, 2008

Rails has a number of helpers which put fairly chunky bits of javascript into your html. This isn’t the purest solution, and is particularly messy for accessibility when javascript is disabled. A number of people have addressed this issue which I’ll discuss here

Fundamental Approach

We keep css in stylesheets, so lets stop embedding javascript in our html and keep it in separate scripts. The issue is then how do we apply our javascript to our html in an effective manner.

The favoured solution is to use lowpro. This is an additional javascript library that clarifies the addition of javascript behaviours to elements in the DOM using css selectors. What this means is that you can write a behavior (say the generation of a form to post a DELETE) which will be applied to all elements with the css class ‘delete_link’. Currently the javascript to do this is a bit hairy for me, but if I can get to grips with it then it should be very cool.

The main effect of this is on the workflow of developing a web app. Basically you can now turn off javascript, get your web app to work properly (ideally with good webrat based story tests), and then add your javascript for extra functionality as a separate process. Done properly this second process won’t touch your html (except perhaps to add css selectors - although they should be already there if your html is semantic).

Need to do a test application to investigate this further.