Page Specific JavaScript in Rails

Rails and the Asset Pipeline #

The Rails asset-pipeline compresses and minifies your JavaScript (or CoffeeScript) and CSS files. It combines your separate JavaScript files into one big file that is delivered by the server, and thereby reduces the number of requests the browser needs to make.

This is well and good, but what happens when you have page-specific JavaScript-files, i.e. scripts you only want to run when certain pages are requested? By default Rails will include these scripts in all the pages.

Page Specific JavaScript #

Let’s say you have a controller users and a corresponding view. You also have a file app/assets/javascripts/users.js that you only want to run when the users page is requested. To make this happen you need to do two things.

First, remove the line //= require_tree . from app/assets/javascripts/application.js. This line instructs Rails to combine all the JS files in the javascripts directory into one single file that will be included with all pages.

Next, you need to instruct Rails to include the users.js file for the users page. Do this by including the following line in the view/layout file for your users controller (embedded the view template language you use): javascript_include_tag params[:controller]

That’s it. Rails will now include your users.js script for the users page only.


Now read this

Breaking out of the For Loop: Pragmatic Functional Techniques in JavaScript

While JavaScript’s simplicity and small size is often an advantage, JS programmers sometimes must restort to techniques that are too low-level and convulted for the problem at hand. With no standard library to speak of, convinient... Continue →