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

1 Min. Read
Sep 11, 2014

 Rails3 Rails Ruby JS Sprockets

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

1
2
3
4
5
//= 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

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

    1
    2
    3
    
        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.

You might also like

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


Write To Me

Hire me shiva bhusal
We'll never share your email with anyone else.
I'll never share your email with anyone else.