Jammit is a great Rails plugin for packaging assets (javascript and stylesheet files). Its installation is as easy as gem install jammit
. If you are on Rails3, you can add it to your Gemfile
:
gem 'jammit', '~>0.5'
Next step is describing your assets in a yaml files with, optionally, some options:
embed_assets: on
javascripts:
workspace:
- public/javascripts/vendor/jquery.js
- public/javascripts/lib/*.js
- public/javascripts/views/**/*.js
- app/views/workspace/*.jst
stylesheets:
common:
- public/stylesheets/reset.css
- public/stylesheets/widgets/*.css
workspace:
- public/stylesheets/pages/workspace.css
empty:
- public/stylesheets/pages/empty.css
Then, you run jammit
, it minifies the files, bundle them and put the compressed results in public/assets
.
Last thing, you should use the new helpers to include your packaged assets in your Rails app:
<%= include_stylesheets :common, :workspace, :media => 'all' %>
<%= include_javascripts :workspace %>
For the minification of your Javascript files, you have the choice between YUI compressor and Closure Compiler, but in both cases, you have to take care of your javascripts. I have three example of gotchas that'll prevent the minifier to do its job (I have experienced them):
Using an already minified of your favorite framework ;
Forgetting a semi-colon in an inline function. Example taken from an old version of jquery.nano :
$.each(keys, function () { value = value[this] })
The semi-colon at the end of line is optional, no problem with it. But the one inside the function is mandatory and you have to put it to satisfy the minifier:
$.each(keys, function () { value = value[this]; })
- Declaring a variable and naming with a reserved keywords like
char
(it's reserved as a future keyword by the ECMAScript):
function hello(char) { alert("hello " + char); }
will fail with some mysterious error messages.
But, using jammit and fixing these problems (if you encounter them) don't take too much time and it's worth it.