6

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.

2 Answers 2

12

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" %>
Sign up to request clarification or add additional context in comments.

1 Comment

Cool, this is how the generated skeleton should have been done. What about actions? I mean... I would like to load a JavaScript only for an specific action... is it also possible to do in an easy way?
3

The require_tree directive in your application.js loads all js and coffee files found in your assets tree. If you remove it it will only load the specified files.

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?

No, files are loaded as specified via "require" directives.

Also... I would like to know how to conditionally include Javascript files depending on the controller's action.

Make a foo_bar.js file for each controller, in each require other files as needed, and conditionally include them in your layout

# some_layout.erb
<%= javascript_include_tag params[:controller] %>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.