Getting Started with Rails 3: Part 2: jQuery
This was a difficult choice to make; I was introduced to Prototype & Scriptaculous through the rails-spinoff project 5 years ago. I credit them with reigniting my interest in the JavaScript language, and front-end web development in general. They advanced the state of the art while simultaneously making development fun again!
They’re mature, stable libraries, and that’s great! But without a major release from them in almost 3 years, alternatives like jQuery (and jQuery UI) have surpassed them in (no particular order): performance, community, training, corporate adoption, ease of use and mobile vision.
So what does this have to do with Rails 3?
Of square pegs & round holes, or, Enter Unobtrusive JavaScript
Taking advantage of the AJAX-enabled view helpers included in Rails (or homegrown) meant tightly coupling our markup (structure) with our JavaScript (behavior). For example, calling link_to_remote() actually outputs <a href="#" onclick="new Ajax.Updater();"> which references the Ajax object from the Prototype library. (The amount and complexity of the JavaScript depends on the options passed to the view helper.)
Rails 3 forgoes emitting JavaScript in favor of data-* attributes from HTML5 and event listeners. Out of the box, those listeners are based on the Prototype API.
(In Part 1, we created a new Rails application and excluded Prototype & Scriptaculous from our project.)
To use jQuery instead, you just need to:
- Download the jQuery adapter from http://github.com/rails/jquery-ujs/raw/master/src/rails.js and save it to the
public/javascriptsdirectory. - Edit
config/application.rband add:
config.action_view.javascript_expansions[:defaults] = %w(http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js rails)
(I’m cheating a little and loading jQuery from the Google CDN.) That was quick: we’ve now configured our application to load jQuery instead of the included JavaScript libraries.
Let’s save our progress again and commit our changes in Git:
$ git add public/javascripts/rails.js $ git commit -a -m "use jQuery instead of Prototype/Scriptaculous" $ git tag part2
(Feel free to fork my Github repository if you’d like to follow along athttp://github.com/defeated/wisdombiscuit)