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.

 
47
Kudos
 
47
Kudos

Now read this

The How to Design Functions Recipe

There’s an interesting course at Coursera — Introduction to Systematic Program Design — that teaches a spesific design process for programming. The course uses Racket, a Scheme dialect, but the design techniques are easily transferable... Continue →