Rails - how to include Javascript files only on certain pages
This is getting old now and we're in a Webpacker world with Rails 6, but if you want to keep things more simple in the old school Sprockets way, you might like the approach described below. Note that it really is per-view - other answers have good approaches for wider scope per-controller stuff.
Have your main layout declare a 'content for' section. For example, in application.htm.erb
:
<!DOCTYPE html>
<html>
<head>
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
...etc...
<%= content_for :head %>
</head>
...
</html>
Here, :head
is just a label and you can give it any name you want. You can have as many such declarations in your layout as you want, too. They're just Rails's way of letting views insert extra stuff into those bits of your outer layout. So - you use this from within individual views to add your JS file(s) <script>
tags inside the <head>
section of the layout.
For example, suppose I have manually "installed" the zxcvbn.js library by copying its one JavaScript file into vendor/assets/javascripts/zxcvbn.js
. I have an edit.html.erb
page where this is required, so at the top of that file, I add:
<% content_for :head do %>
<%= javascript_include_tag('zxcvbn', 'data-turbolinks-track': 'reload') %>
<% end %>
...removing the Turbolinks attribute if you're not using it. This means that when ERB compiles the page, it'll substitute that tag inside the 'content for head' part of the layout, so the script tag ends up in its place. This will of course mean an extra HTTP fetch when the page loads, but only in the views where it is used. In the above example the JS library is pretty big and would usually only used for one or two places related to users changing passwords; so this is a big win over having it lumped into a compiled application.js
and served everywhere, even though it's almost never used.
The content_for
stuff is quite clever by virtue of being quite simple under the hood. If your view was built from several partials, with more than one of them making the declarations, they don't overwrite each other. Each just gets concatenated into the right place, so the end result is pretty much what you'd expect without any nasty surprises.
There's one more step you need to avoid an exception from Sprockets because the asset you're trying to include isn't precompiled. You need to tell Sprockets it exists; for some reason, that's not automatically determined. In config/initializers/assets.rb
, declare "out-of-band" / unknown files that aren't otherwise included in the e.g. application.js
manifest file:
Rails.application.config.assets.precompile += %w( zxcvbn.js )
The out-of-box Rails-generated assets.rb
has comments explaining this and a commented-out example in place.
This is all cooperating normally with the asset pipeline, so it works as well (or badly, depending on your experience!) as anything else in the pipeline, with debug versions in development mode and minified content in production (subject to your pipeline configuration).
You can put any Javascript files that you want to load manually in the public/javascripts/lib
directory of your application, and they will not be included in the assets pipeline. You can then load them manually on the pages that need them.
For instance, in one project, I use the Chosen jQuery plugin, and I load it like so:
<script type="text/javascript" src="/javascripts/lib/chosen.jquery.min.js"></script>
Rails will source the public files from public/
, so you only need to reference your files from there (remove the public/
bit).
This project is fairly large, with 88 controllers, 662 actions, and a total of 38 custom javascript libraries that get used sporadically around the app, including markdown editors, charting libraries, and even jQuery UI.
To manage the sprawl and to keep each page as tight as possible, I have done 2 things: 1) in my controller, I set an instance variable,@page_libs
, to list the libs to load, and 2) the layout uses the values in @page_libs
to include the specialty Javascript when required.
A controller action might look like this:
def edit
@products = products.find(params[:id])
@page_libs = [:ui, :textile]
end
And the app/views/layouts/application.html.erb
includes this in the correct place:
<%- if @page_libs&.include?(:ui) || @page_libs&.include?(:table) %>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script type="text/javascript" src="/javascripts/lib/chosen.jquery.min.js"></script>
<% end -%>
<%- if @page_libs&.include?(:swiper) %>
<script type="text/javascript" src="/javascripts/lib/idangerous.swiper.min.js"></script>
<% end -%>
<%- if @page_libs&.include?(:table) %>
<script type="text/javascript" src="/javascripts/lib/jquery.handsontable.full.js"></script>
<% end -%>
<%- if @page_libs&.include?(:textile) %>
<script type="text/javascript" src="/javascripts/lib/textile.js" charset="utf-8"></script>
<% end -%>
Note that the first include is for jQuery UI, which I load from a CDN, rather than from my app's public
. This technique works just as well with external libraries, as well as those that you host. In fact, most pages in my app only depend on 2 external libraries (jQuery and Underscore.js), but have the option of loading up to 16 other Javascript libraries from external sources. Limiting external libraries on the page can significantly reduce your page load times, which is a direct performance boost for your application.
Sometimes, a Javascript library will include CSS components, as well. Or, you may even have page-specific CSS to include. The same approach can be taken with external stylesheet. These are the corresponding page-specific stylesheet "includes" for the above Javascript libraries:
<%- if @page_libs&.include?(:ui) %>
<link rel="stylesheet" type="text/css" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="/stylesheets/lib/chosen.min.css">
<% end -%>
<%- if @page_libs&.include?(:swiper) %>
<link rel="stylesheet" type="text/css" href="/stylesheets/lib/idangerous.swiper.css">
<% end -%>
This way, I have a single point in the project to manage the libraries, regardless of how many (or few) are required for a page. I'll probably eventually create a series of custom before_action
handlers in the ApplicationController to define which the libraries a page needs included. Something like this:
before_action: :include_library_ui, only: [:new, :edit]
before_action: :include_library_swiper, only: [:show]
This would clean up the controller actions a bit more and make it easier to identify dependencies. However, given the size of my codebase and the pressing tasks remaining, I haven't taken this leap yet. Maybe it will inspire you to do so to start out.