matterkkila.com/

code monkey

javascript standards and practice

September 16, 2007 - 12:34 PM

I had a thriving discussion on the standards and practices for using javascript. The debate largely centers around two main methods of using and initating javascript on a webpage. Back when I first started writing javascript, about 8 years ago) creating a <a href="#" onClick="" was completely acceptable. But this lends itself to a combined page of html and javascript. Which isn't that big of a deal on smaller pages. But when you have a large page it quickly becomes cluttered. In the past we have moved cascading style sheets and javascript to a separate file with only pointers being left in the original page. However the expansion of javascript and the use of XMLHttpRequest has seen more and more 'pointers' being left in html documents, quickly destroying the purpose behind the separate javascript file.

While this isn't a new idea it is one I have just started to embrace more of in the last few months. Using the JQuery and/or prototype library to attach javascript on the fly to the DOM, adding event handlers at runtime. This allows for a very clean separation of logic. The template used for display will contain only the html layout and the javascript file will contain all the definitions of events and actions which can be performed and then attach themselves at the proper place in the DOM. While this makes debugging a little more difficult, especially if you are not the original programmer, I believe that the overall benefit of this design practice will lend itself to a code base which is much easier to maintain.

Posted In: