I understand the "why" part of "why do all js / css files get included in rails asset pipeline" as explained here.
However, that's not always desirable, is it? For instance, I have a non-standard layout I use just to display items that require Google maps. I don't want all the external gmap libraries included on all pages-- it's not necessary and is just wasteful-- but if I don't include them on every page, the calls to the google api in the
map.js.coffee files will throw errors.
Is there a way to force the
map.js.coffee ONLY show on a
Best How To :
To combine what the other answers suggested and other sources on the web advised, it seems like the best answer to this situation is to do the following:
Create subdirectories in the
assets/stylesheets directories as well as
maps.css files. In my example above you'd have
maps.js file would look like:
//= require_tree ./maps
which will include all items in the maps directory / subdirectories.
application.js is the same but includes the "main" site resources as well as any site-specific items:
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap
//= require_tree ./site
Create a maps layout file called
views/layouts/maps.html.erb, and in the layout file, use the
<%= stylesheet_link_tag "maps", media: "all", "data-turbolinks-track" => true %>
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
Make sure the
MapsController specifies the maps layout!
class MapsController < ApplicationController