Using Jammit in Rails  

21 Jul 2011
William Notowidagdo Kiranatama Staff
Knowledge


I'll show you how to easily integrate Jammit in a Rails 3 application.

Background

In web application today that are very common that we have 3 to 5+ script and CSS files. Using Jammit we can combine (or in this context: package) all scripts into a single script, and similarly combine all CSS into single stylesheet. Reducing the number of HTTP requests can lead to a faster page loading.

Installation

In your Gemfile

gem 'jammit', '~> 0.6.3', :groups => [:development, :production]

then run

$ bundle install

I put jammit on development too since I want to check the joint script and stylesheet is working.

Configuration

Create config/assets.yml. Here is an example

package_assets: on
compress_assets: on
embed_assets: off
javascripts:
  common:
    - public/javascripts/jquery.js
    - public/javascripts/rails.js
    - public/javascripts/jquery/jquery-1.4.4.js
    - public/javascripts/jquery/jquery.labelify.js
    - public/javascripts/jquery/jquery-ui-1.8.9.custom.min.js
    - public/javascripts/jquery/jquery.colorbox.js
    - public/javascripts/prettyCheckboxes.js
    - public/javascripts/jquery.numeric.js
    - public/javascripts/application.js
stylesheets:
  common:
    - public/stylesheets/960.css
    - public/stylesheets/style.css
    - public/stylesheets/prettyCheckboxes.css
    - public/stylesheets/humanity/jquery-ui-1.8.9.custom.css
    - public/stylesheets/colorbox.css
    - public/stylesheets/overide.css
    - public/stylesheets/multipleselectbox.css

See here for complete configuration options that you may add to assets.yml

Usage

In your layout

<%= include_stylesheets :common :media => 'all' %>
<%= include_javascripts :common %>

In development, no packaging is performed, unless package_assets is set to "always".

Tips

  1. Include only script and CSS that you need
  2. Pay attention on the file order. You need to know what file that must be loaded first before others.
  3. Using above method, jammit will try to package and compress script and CSS files by request, it is better if you can use Jammit within your Rakefile and run the task only when you need to deploy your application to a production server.