Rails Basics - Adding page specific javascript to your view

These “Rails Basics” blog posts are simple how-to’s for Rails 3. These are aimed at beginners to Rails, but prior programming knowledge will be helpful.

To be able to include page specific javascript in the <head> of your page, you need to first add a new yield to your layout page (typically application.html.erb).

This can be seen below, I have named this yield "head".

<head>
  <title>My cool web app</title>
  <%= csrf_meta_tag %>
  <%= javascript_include_tag :defaults %>
  <%= javascript_include_tag 'jquery-1.4.3.min', 'jquery-ui-1.8.5.custom.min', 'fullcalendar.min' %>
  <%= stylesheet_link_tag 'scaffold', :media => 'screen' %>
  <%= yield(:head) %>
</head>

This is basically a placeholder that you can now access from your views.

In your view, you now add the following code:

<% content_for(:head) do %>
  <%= javascript_include_tag 'my_page_specific_javascript_file' %>
<% end %>

In the above code, replace my_page_specific_javascript_file with the name of your .js file (exluding the .js). You will also need to add your javascript file to the javascripts folder.

That is all that is required. The same concept can be used to inject anything into the <head> of your page from your view.

By Joel Friedlaender