Speeding Up the Front-end with Rails
7 months ago
Much can be done to optimize the front-end of your web application, and Rails has some great mechanisms built in to help you do that. Here are a few front-end engineering tips, and a bit of Rails coolness, that can make your pages load faster.
Tip #1 – Add a far future expires and max-age header to your static assets. This will tell the browser to check its cache first for an asset before initiating an HTTP request. If any of your static assets change before the expires date is reached, or the max-age is achieved, Rails will “rev” your files. If you’ve ever looked at your javascript files or stylesheets when doing a View Source, you’ve probably noticed that Rails adds a timestamp to these assets which represents the latest date they were modified. Change any of the files, and Rails will update the timestamp, forcing the browser to make a request for a file it now considers new.
Tip #2 – Use the “:cache” directive when linking to a javascript file. If you’re linking to multiple javascript files and you use this directive, Rails will combine all separate files into one, thereby eliminating multiple requests.
true %>
Tip #3 – Do the same for stylesheets – use the “:cache” directive to combine all stylesheets.
<%= stylesheet_link_tag :all, :cache => true %>
Tip #4 – You can use the asset_packager plugin to combine all javascript files and stylesheets together into one file AND minify them all at the same time.
Tip #5 – If you’re using commonly used javascript libraries like jQuery or Prototype, use Google’s version instead of one that’s located in your app. It’s probable that a user already has one of Google’s many cached javascript libraries, so you can shave off an additional HTTP request.