This is the default application.js:
//= require jquery
//= require jquery_ujs
//= require_tree .
CoffeeScript templates have this content:
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
For me, “related to the matching controller here” means that foo_bar.js.coffee should ONLY be loaded when the foo_bar controller is used. Am I right?
Thing is that it loads all Javascript files even if they are not needed. Also… I would like to know how to conditionally include Javascript files depending on the controller’s action.
A couple of ways to do this, the easiest and most elegant way I have found is this:
Remove the
Directive, and change your template to
Then load your global js in application, and controller specific in controller_name.
For instance, if you are in posts_controller, you will get posts.js or posts.js.coffee loaded.
EDIT
To do the action, you can also add
to my proposed solution. One thing you may consider, is breaking it out into application_controller.rb:
Then using it like this in your layout