Shiva Bhusal
Shiva's Blog

Follow

Shiva's Blog

Follow

Rails 3.1 and Higher: Load Controller Specific Scripts (css, js)

Shiva Bhusal's photo
Shiva Bhusal
·Sep 11, 2014·

2 min read

Play this article

Sprockets

Sprockets is a Ruby library for compiling and serving web assets. It features declarative dependency management for JavaScript and CSS assets, as well as a powerful preprocessor pipeline that allows you to write assets in languages like CoffeeScript, Sass and SCSS.

Rails has a feature of loading scripts automatically when included in application.js or css like

//= require jquery
//= require jquery_ujs

//code below in the application.js file tells to load every script in the tree.
//= require_tree

Now for common scripts you can use above method but, if you want to load controller specific scripts the you can follow the steps below:

Controller specific Scripts

You can load controller specific js files in the views, instead of loading a whole JS files a single file application.js

For large web apps, you might have 10 MB of JS; loading this at a time might be time consuming. So, you can divide the JSes into separate files per controller like modern Rails suggests. For example controller1.js for controller1 controller.

Advantages

  • Faster page loading time
  • Prevents JS back-firing issue when, JS event targetted for button in controller1 triggers button in controller2

Disadvantage

  • If users need to use all the controllers, he yet has to load many js files instead a single application.js

How?

  1. Add controller_name in the following line in file views/layout/application.html.erb

         <%= javascript_include_tag 'application', controller_name %>
    
  2. Add the following line in /config/initilizers/assets.rb to precompile additional assets.

         Rails.application.config.assets.precompile += %w( bids.js )
         Rails.application.config.assets.precompile += %w( controller1.js )
         Rails.application.config.assets.precompile += %w( controller2.js )
    
  3. After Changing settings inside any file within config folder, you need to restart the server.

 
Share this