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

Rapid Prototyping with Meteor.js

This tutorial assumes that you have Node.js and Meteor installed. Step 1: Create a meteor app # Creating a new app in Meteor is very easy: $ meteor create chat To start Meteor we cd into the newly created directory and simply type... Continue →