Although I’ve stuck with prototype & script.aculo.us for gsnowdon.com for the last few years my wife has requested a major re-working of the way the product management pages work and I thought that I’d bite the bullet and port the site to jQuery and then use that for all the new functionality.
The first thing to note is that the management.js file dropped from 948 lines to 802 although some of this is due to differences in the way I tend to format jQuery code. Perhaps a better comparison is file size which dropped from 34,732 bytes to 29,259.
The biggest wins were code fragements such as the following:
which become one-liners in jQuery:
The ability to chain a sequence of jQuery operations also helps to make code more concise, as in:
The original code made quite a lot of use of Prototype’s collect() function as in:
I’d then use join() on the resulting HTML to create a string I could stuff into the innerHTML of a container element. Jquery does not seem to have a collect() function so I used the following implementation from
The arguments are reversed compared to the prototype equivalent but I like this ordering better.
There’s not a great deal of difference when making AJAX requests between Prototype and jQuery as the following shows; although the ability of jQuery to automatically process JSON and pass an object rather than a string back to the callback did make the code marginally more concise:
I could have used $.get() and $.post() to make the jQuery versions a litle bit more concise but didn’t bother in this case.
There were also a number of cases where code like this:
got re-written as below. The only advantage in doing things the jQuery way in this case is that the code would still work no matter what HTML form widget is used.
There’s a lot more I could do to improve the current code. I didn’t make use of any jQuery plugins. For example I could have used Jeditable to replace some home-grown edit-in-place code but that can wait until I start re-working the user interface as I intend to make some significant changes.