Inspired by the recent launch of code.google.com/speed, I decided to sit down and see how I could apply their guidelines. This is the first in a series of posts on improving front-end performance for your Rails applications.
First of all, we need to create our sample application. Recently, I’ve been using Beet, a gem for generating Ruby projects, but you can create your local version however works for you. Using Beet, the following command tells the Rails generator to use MySQL, remove unused files (public/index.html, etc.) and initialize a Git repository:
beet -g built_for_speed -r="rails/db/mysql, rails/clean_files, rails/git"
Next, let’s create a Post resource:
script/generate scaffold Post title:string body:text
Make sure your databases are created, and run the migrations. Note that for the purposes of this tutorial, I’m running the application in production mode (to better see the speed benefits), using Passenger on my MacBook Pro. By the way, I highly recommend the Fingertips Passenger preference pane for managing your sites locally.
RAILS_ENV=production rake db:migrate
Now let’s add the Blueprint CSS framework. Download the latest version from blueprintcss.org and unpack it somewhere. Blueprint provides you with compressed versions of the CSS files, but humor me and add the uncompressed versions. From the unpacked directory, copy all the CSS files from /blueprint/src/ into /public/stylesheets/blueprint/ in your application.
Okay, now let’s fire up the application. I’ll be using Firefox so we can profile the application using YSlow. Go ahead and create your first post. Once you’re looking at the ‘show’ page, let’s open up Firebug and click on the “YSlow” tab. On the YSlow screen, click the “Run Test” button to get your page grade.
Bummer, we got an overall D – not so good. Let’s take a look at what’s going on. YSlow grades are listed in order of importance, so let’s check out the first section: “Make fewer HTTP requests”. Looks like we got a C in that area. What can we do to improve our grade? YSlow gives us some tips: “combine multiple scripts into one script, combine multiple CSS files into one style sheet”. Before we get back to the application, take a look at the “Components” tab in the YSlow dialog.
script/plugin install git://github.com/sbecker/asset_packager.git
The first step after installation is to create the configuration file for AssetPackager:
$ rake asset:packager:create_yml
Okay, now it’s time to see the fruits of our labors. Restart the application in the Passenger preference pane, and reload the post page in Firefox. Now let’s run YSlow again. This time, you should see output like this:
Alright! We’ve improved our grade up to an overall B, with an A for “Make fewer HTTP requests”. Let’s take a look at the ‘Components’ tab.
The source code for this sample application can be found at: github.com/dramsay/built_for_speed
Check back for more performance tips in the future.