Rails 3.1 asset pipeline: how to load controller-specific scripts?

To load only the necessary name_of_the_js_file.js file:

  1. remove the //=require_tree from application.js

  2. keep your js file (that you want to load when a specific page is loaded) in the asset pipeline

  3. add a helper in application_helper.rb

    def javascript(*files)
      content_for(:head) { javascript_include_tag(*files) }
    end
    
  4. yield into your layout:

    <%= yield(:head) %>
    
  5. add this in your view file:

    <% javascript 'name_of_the_js_file' %>
    

Then it should be ok


An elegant solution for this is to require controller_name in your javascript_include_tag

see http://apidock.com/rails/ActionController/Metal/controller_name/class

<%= javascript_include_tag "application", controller_name %>

controller_name.js will be loaded and is in the asset also, so you can require other files from here.

Example, rendering cars#index will give

<%= javascript_include_tag "application", "cars" %>

where cars.js can contain

//= require wheel
//= require tyre

Enjoy !