Best way to add page specific JavaScript in a Rails 3 app?
What I like to do is include the per-view Javascript in a content_for :head
block and then yield
to that block in your application layout. For example
If it's pretty short then:
<% content_for :head do %>
<script type="text/javascript">
$(function() {
$('user_rating_positve').click(function() {
$('some_div').show();
}
});
</script>
<% end %>
or, if longer, then:
<% content_for :head do %>
<script type="text/javascript">
<%= render :partial => "my_view_javascript"
</script>
<% end %>
Then, in your layout file
<head>
...
<%= yield :head %>
</head>
If you want to include javascript just on one page, you can include it on the page inline of course, however if you want to group your javascript and take advantage of the asset pipeline, minified js etc, it's possible to do so and have extra js assets which are combined and only loaded on specific pages by splitting your js into groups which only apply in certain controllers/views/sections of the site.
Move your js in assets into folders, with a separate manifest file for each, so if you had an admin js library that is only used on the backend, you might do this:
- assets
- javascripts
- admin
- ...js
- admin.js (manifest for admin group)
- application.js (manifest for app global group)
- global
- ...js
- admin
- javascripts
in the existing application.js
//= require jquery
//= require jquery_ujs
//= require_tree ./global // requires all js files in global folder
in a new admin.js manifest file
//= require_tree ./admin // requires all js files in admin folder
Make sure this new js manifest is loaded by editing config/production.rb
config.assets.precompile += %w( admin.js )
Then adjust your page layout so that you can include some extra js for the page head:
<%= content_for :header %>
Then in views where you want to include this specific js group (as well as the normal application group) and/or any page-specific js, css etc:
<% content_for :header do %>
<%= javascript_include_tag 'admin' %>
<% end %>
You can of course do the same thing with css and group it in a similar way for applying only to certain areas of the site.