Compress Rails App for good

Many years ago I was working on a web app for embedded web server. When our team learnt about javascript minifier, html compressor and other tools are freely available, we were pretty excited. What you may think is about the saving of loading time but it was the saving of device’s ROM usage that makes us (including our boss) excited :-)

Today as I am working on a Rails web app, to my surprise the html, CSS and javascript are not compressed or minified by default. Although my web app is not big and there is no speed issue, I felt it is still good (to be a good web citizen?) to do so. Besides, it is a big surprise to see how much it saved after compression!

First, add following two gems to Gemfile

gem ‘htmlcompressor’
gem ‘yui-compressor’

don’t forget to do “bundle install”.

Then add following lines to “application.rb” (tested on Rails 4, Rails 3 might be different)

config.middleware.use Rack::Deflater
@options = {
:enabled => true,
:remove_multi_spaces => true,
:remove_comments => true,
:remove_intertag_spaces => true,
:remove_quotes => false,
:compress_css => true,
:css_compressor => :yui,
:compress_javascript => true,
:javascript_compressor => :yui,
:simple_doctype => true,
:remove_script_attributes => false,
:remove_style_attributes => false,
:remove_link_attributes => false,
:remove_form_attributes => false,
:remove_input_attributes => false,
:remove_javascript_protocol => false,
:remove_http_protocol => false,
:remove_https_protocol => false,
:preserve_line_breaks => false,
:simple_boolean_attributes => false,
:compress_js_templates => false
}
config.middleware.use HtmlCompressor::Rack, @options

With this changes, it reduced the web app root page from 23.3KB to 5.2KB!

Hopefully, this could motivate more to be a good web citizen :-)

Like what you read? Give suising a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.