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
//= require_tree .
Directive, and change your template to
<%= javascript_include_tag "application", controller_name %>
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
action_name
to my proposed solution. One thing you may consider, is breaking it out into application_controller.rb:
before_filter :your_function
def your_function
@controller = controller_name
@action = action_name
end
Then using it like this in your layout
<%= javascript_include_tag "application", "#@controller.#@action" %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With