Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a Javascript asset depending on controller/action?

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.

like image 911
Cristian Avatar asked Dec 11 '11 22:12

Cristian


1 Answers

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" %>
like image 109
andrewpthorp Avatar answered Nov 14 '22 23:11

andrewpthorp