Including jQuery in your Rails app
If you’re loving jQuery for one reason or another (simple DOM manipulation for one) and you’re thinking about using it in a Rails project or three, this little gotcha may have you scratching your head.
Let’s say you’ve been using the default javascript libraries and writing all your little functions in application.js like a good boy, then you decide to include the jQuery library and play around. It probably looks something like this:
1 <%= javascript_include_tag :defaults, "jquery" %>
So you code up some jQuery hackery in application.js and are having so much fun that you decide to ditch the default libraries outright. Yea Yea! You change your include to look like this:
1 <%= javascript_include_tag "application", "jquery" %>
Suddenly none of your jQuery functions are firing! What What What?!?!
The order of javascript includes matter, so you have to load your jQuery library before loading your application.js file. Change your include to look like this:
1 <%= javascript_include_tag "jquery","application %>
Ahh, that’s better!
If you’re wondering why it was working before when you were loading the :defaults before the jQuery library, its because Rails is smart enough to know that application.js needs to be loaded last no matter what, so it will load all the libraries and then append application.js to the end. Very nice.
