1
votes

I think the docs http://guides.rubyonrails.org/asset_pipeline.html need some clarification. They state:

For example, if a ProjectsController is generated, there will be a new file at app/assets/javascripts/projects.js.coffee and another at app/assets/stylesheets/projects.css.scss. You should put any JavaScript or CSS unique to a controller inside their respective asset files, as these files can then be loaded just for these controllers with lines such as <%= javascript_include_tag params[:controller] %> or <%= stylesheet_link_tag params[:controller] %>.

It is my understanding that in production mode, all JS gets packaged up into one optimized file, preferably. I'm guessing that caching of this optimized file is preferable to having pages specifically loading different sets of JS files themselves.

Maybe the point of the javascript_include_tag is to RUN some specific javascript to that page. However, the default for application.js is to include the tree, which includes the generated files. So I'm guessing that would have to be adjusted to NOT include any controller specific javascript.

This answer here Using Rails 3.1, where do you put your "page specific" javascript code? seems to suggest a reasonable way of handling the issue is to associate JS features with divs, and when JQuery does not see the div on the page, nothing is executed.

So what is the best practice? Is my understanding of the controller specific divs correct? Does the default to include the tree inside of application.js conflict with the goals of controller specific js?

2

2 Answers

0
votes

You shouldn't rely on the application.js scaffold in my opinion. application.js requires the whole tree, but this is done to make it easy to start a project, it doesn't mean it's supposed to stay this way.

It's likely that you will create different "bundles" of files, some of them will just be included in specific pages.
For instance, my application.js just requires librairies and every files in an application folder. This way you can still have page specific js.

I guess that <%= javascript_include_tag params[:controller] %> can be useful if you have big javascript files specific to some controller.

0
votes

It does conflict - you should pick one approach (require_tree) or the other (load each controller file).

The first is optimal, and it is simple to target page-specific js with css classes.

The only time you'd not want to do this is for admin sections (where you'd use a second manifest) or some other specialist feature like a lightbox gallery that is only on specific pages (so you don't want the extra js and css everywhere on the site).