How to load Javascript resource depending on controller / action?

This is the default value 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, “ associated with the appropriate controller here ” means it foo_bar.js.coffeeshould ONLY load when the controller is in use foo_bar. I'm right?

The fact is that it downloads all Javascript files, even if they are not needed. Also ... I would like to know how to conditionally include Javascript files depending on the action of the controller.

+5
source share
2 answers

A few ways to do this, the easiest and most elegant way I've found, are as follows:

Remove

//= require_tree .

and change your template to

<%= javascript_include_tag "application", controller_name %>

js , _.

, posts_controller, posts.js posts.js.coffee.

,

action_name

. , , application_controller.rb:

before_filter :your_function

def your_function
  @controller = controller_name
  @action = action_name
end

,

<%= javascript_include_tag "application", "#@controller.#@action" %>
+12

require_tree application.js js coffee, . , .

" " , foo_bar.js.coffee , foo_bar. ?

, "require".

... , Javascript .

foo_bar.js ,

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

All Articles