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

Mike Bevz picture Mike Bevz · Jul 4, 2011 · Viewed 36.6k times · Source

If I generate a new controller in Rails 3.1, also a javascript file with the name of the controller will added automatically. Firstly, I thought this javascript file will used only, when the related controller is called.

By default there is the instruction //= require_tree . in the application.js-file, that include every javascript file on it's tree.

How could I load only the controller specific script?

Answer

Nguyen Chien Cong picture Nguyen Chien Cong · Jul 22, 2011

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