Jammit

Jammit is an industrial strength asset packaging library for Rails, providing both the CSS and JavaScript concatenation and compression that you'd expect, as well as YUI Compressor and Closure Compiler compatibility, ahead-of-time gzipping, built-in JavaScript template support, and optional Data-URI / MHTML image embedding.

Jammit is an open-source component of DocumentCloud.

Table of Contents

Installation | Configuration | Usage | YUI & Closure | Precaching Assets
Embedding Images | JavaScript Templates | Change Log

Links

Source Code | Internal Docs | Image Embedding Example

Installation

  1. Grab the gem:
    gem install jammit
  2. Add the gem to Rails' environment.rb inside of the initializer:
    config.gem "jammit"
  3. Edit config/routes.rb to give Jammit a route ( /assets by default) for dynamic asset packaging and caching:

    ActionController::Routing::Routes.draw do |map|
      ...
      Jammit::Routes.draw(map)
      ...
    end

Note: If you don't already have the ruby-yui-compressor or closure-compiler gems installed, downloading make take a minute — the jar files together weigh in at 5 megabytes.

Configuration

Jammit uses the config/assets.yml YAML configuration file to define packages and to set extra options. A package is an ordered set of directory glob rules that will be expanded into a unique list of files. An example of a complete assets.yml follows:

embed_images: on

javascripts:
  workspace:
    - public/javascripts/vendor/jquery.js
    - public/javascripts/lib/*.js
    - public/javascripts/views/**/*.js

stylesheets:
  common:
    - public/stylesheets/reset.css
    - public/stylesheets/widgets/*.css
  workspace:
    - public/stylesheets/pages/workspace.css
  empty:
    - public/stylesheets/pages/empty.css

templates:
  everything:
    - app/views/jst/**/*.jst

There are a number of extra configuration options that you may add to the assets.yml configuration file to customize the way Jammit behaves. Here's an example configuration file using all of the possible options. The meaning of the options and their default values are listed below:

package_assets on | off | always Defaults to on, packaging and caching assets in every environment but development. Never packages when off, always packages when always.
javascript_compressor yui | closure Defaults to yui. As of 0.2.0, the Jammit gem can use either the YUI Compressor or the Google Closure Compiler to compress your JavaScript.
embed_images on | off | datauri Defaults to off. When on, packages and caches Data-URI and MTHML variants of your stylesheets, with whitelisted images embedded inline. Using datauri serves embedded images only to browsers that support Data-URIs, and serves unmodified stylesheets to Internet Explorer 7 or lower.
compress_assets on | off Defaults to on. When off, JavaScript and CSS packages will be left uncompressed. Disabling compression is only recommended if you're packaging assets in development.
template_function on | off | ... The JavaScript function that compiles your JavaScript templates (JST). Defaults to on, which uses a bundled variant of Micro-Templating. Set it to _.template if you use Underscore.js, or new Template for Prototype. Turn it off to pass through the template strings unaltered.
package_path ... The URL at which packaged assets are cached and made available. Defaults to assets, but if you already have an existing AssetsController with a different purpose, you could change it to, say, packages. (Single directory names only, please.)
compressor_options ... Pass an options hash directly to the underlying JavaScript compressor to configure it. See the ruby-yui-compressor or closure-compiler gem documentation for the full list of available options.
css_compressor_options ... Pass an options hash directly to the YUI CSS Compressor. Available options are charset, and line_break, which can be used to write out each CSS rule on a separate line.

Usage

To access your packages in views, use the corresponding helper. The helper methods can include multiple packages at once:

<%= include_stylesheets :common, :workspace, :media => 'all' %>
<%= include_javascripts :workspace %>
<%= include_templates :everything %>

In development, no packaging is performed, so you'll see a list of individual references to all of the JavaScript and CSS files. The assets.yml configuration file is reloaded on every development request, so you can change the contents of your packages without needing to restart Rails. In all other environments, or if package_assets is set to "always", you'll get tags for the merged packages.

It's recommended to keep the default behavior of unpackaged assets in development, because it's so much easier to debug JavaScript that way. But if you'd like to use fully packaged assets in development, while only rebuilding the packages whose sources have changed between requests, use "always" and add the following before_filter to your ApplicationController to keep your packages fresh:

before_filter { Jammit.packager.precache_all } if Rails.env.development?

YUI & Closure

Jammit can be configured to use either the YUI Compressor or the Google Closure Compiler to compress and optimize your JavaScript. (CSS is always run through the YUI Compressor.) Specify the javascript_compressor to choose either yui or closure backends. If left blank, Jammit defaults to yui.

You can configure the JavaScript compilation by adding compressor_options to your assets.yml. The compressor_options will be passed directly to the Gem backend of your chosen compressor. See the ruby-yui-compressor or closure-compiler gem documentation for all the available options. For example, to configure the Closure Compiler to use its advanced optimizations, you would add the compilation_level:

javascript_compressor: closure
compressor_options:
  compilation_level: "ADVANCED_OPTIMIZATIONS"

Jammit always uses the YUI CSS Compressor to compress CSS files. You can configure it by specifying the css_compressor_options, in assets.yml.

Precaching Assets

Installing the Jammit gem provides the optional but handy jammit command-line utility, which can be hooked into your deployment process. The jammit command reads in your configuration file, generates all of the defined packages, and gzips them at the highest compression setting. In order to serve these static gzipped versions, configure your Nginx http_gzip_static_module, or your Apache Content Negotiation MultiViews. It's also a good idea to have gzip compression turned on for the remainder of your static assets, including any asset packages that aren't gzipped-in-advance. Adding Nginx's http_gzip_module or Apache's mod_deflate will do the trick.

The jammit command can be passed options to configure the path to assets.yml, and the output directory in which all packages are compiled. Run jammit --help to see all of the options. For speedy builds, jammit will check the modification times of your packages and source files: only the packages that have changed are rebuilt. If you'd like to force all packages to build, use jammit --force.

Embedding Images

After you've finished concatenating and compressing your JavaScript and CSS files into streamlined downloads, the slowest part of your page load is probably the images. It's common to use image sprites to avoid the avalanche of HTTP requests that are needed to load a bunch of small images. Unfortunately, image sprites can be complicated to position (especially with horizontal and vertical tiling), and a real pain to create and maintain. With a little elbow grease from Jammit, your spriting woes can be a thing of the past.

With embed_images turned on, Jammit will inline image files directly into your compiled CSS, using Data-URIs in supported browsers, and MHTML in Internet Explorer 7 and below. Instead of ten CSS files referencing 30 images, you can have a single, packaged, minified, gzipped CSS file, with the images coming in all at once instead of piecemeal, making just a single HTTP request.

Take a look at this example (especially on a slow connection or wifi):
Normal Image Loading vs. Jammit Image Embedding

Embedded images can be a little tricky, which is why using them is strictly on an opt-in basis. After enabling embed_images in the configuration file, you'll need to whitelist the images that you'd like to make embeddable. When processing CSS, Jammit will only embed images that have .../embed/... somewhere in their path — the other images will be left untouched. You can make a single public/images/embed folder for your embedded images, or organize them into directories however you prefer. It's not recommended to embed all of your site's images, just the ones that conform to the following three rules:

  1. Images that are small. Large images will simply delay the rendering of your CSS. Jammit won't embed images larger than 32 kilobytes, because Internet Explorer 8 won't render them.
  2. Images that are immediately visible. It's better to leave the images that are hidden at page load time to download in the background.
  3. Images that are referenced by a single CSS rule. Referencing the same embedded image in multiple rules will cause that image's contents to be embedded more than once, defeating the purpose. Replace the duplicated rules with an image-specific HTML class, and you're good to go.

A final cautionary note. Internet Explorer's implementation of MHTML requires the use of absolute paths in image references. This means that the timestamp that Rails appends to the stylesheet URL (to allow far-future expires headers) needs to also be in the contents of the stylesheet. If a process on your webserver changes the modification time of the cached MHTML stylesheet, it will break the image references. To fix it, use the jammit command (with --base-url) to rebuild your assets, or simply delete the cached file, and let Jammit automatically rebuild the file on the next request.

If the MHTML stylesheets sound too fragile, or if you encounter any problems with them in Internet Explorer (such as mixed-mode warnings when serving MHTML through SSL), we recommend setting embed_images to "datauri". Using "datauri" will cause Internet Explorer 7 and below to receive plain versions of the packaged stylesheets, while all other browsers get the Data-URI flavor.

JavaScript Templates

If you're using enough JavaScript to want it compressed and concatenated, you're probably using it to generate at least a little of your HTML. Traditionally, this has been accomplished by joining together strings and inserting them into the DOM. A far more agreeable way to generate HTML on the client is to use JavaScript templates (JST). Think Rails views and ERB, but with interpolated JavaScript instead.

Jammit helps keep your JavaScript views organized alongside your Rails views, bundling them together into packages, and providing them as functions for your client-side code to evaluate. By default, Jammit uses a variant of John Resig's Micro Templating to compile the templates, but you can use a JavaScript templating function of your choosing by specifying a template_function in assets.yml. Jammit will run all of your JST through the template function, and assign it by filename to a top-level JST object. For example, the following template, app/views/jst/license.jst:

<div class="drivers-license">
  <h2>Name: <%= name %></h2>
  <em>Hometown: <%= birthplace %></em>
  <div class="biography">
    <%= bio %>
  </div>
</div>

Including the asset package makes this template available to your JavaScript as the JST.license function.

JST.license({name : "Moe", birthplace : "Brooklyn", bio : "Moe was always..."});

To use Underscore.js templates, set template_function to "_.template".
To use Prototype templates, set it to "new Template".
To use Mustache.js templates, you'll need a little extra setup.

Change Log

0.3.3
Added css_compressor_options to assets.yml, so you can use the charset and line_break options.

0.3.2
If Java isn't available on your machine, Jammit will now run in a graceful degraded mode, where assets are packaged but not compressed. You can now pass :embed_images => false to the include_stylesheets helper to disable image embedding on a per-package basis.

0.2.8
Jammit now correctly rewrites relative image URLs within CSS, for easier integration with partial Rails apps deployed on sub-paths.

0.2.7
The jammit command has been enhanced to check the modification times of your packages — if no source files have changed, the package isn't rebuilt.

0.2.6
Jammit now raises an exception if Java isn't installed, or if the Java version is unsupported by your JavaScript compressor of choice.

0.2.5
When specifying your asset packages as directory globs, absolute globs are now absolute, and relative globs are relative to RAILS_ROOT.

0.2.4
Jammit now throws a ConfigurationNotFound error when attempting to load a nonexistent configuration file. Resolved an issue with asset caching from daemonized mongrels.

0.2.1
The include_stylesheets helper now takes the same options as the Rails stylesheet_link_tag helper (such as :media => 'print').

0.2.0
Jammit now supports the Google Closure Compiler as an alternative to the YUI compressor.

0.1.3
Fixed a bug that conflicted with other plugins trying to alter ApplicationController in development.

0.1.1
Added support for embedding images with stylesheet-relative paths. Shortened the MHTML identifiers.

0.1.0
Initial Jammit release.


A DocumentCloud Project