views:

149

answers:

2

Hello all,

I'm very curious how your Rails apps include javascript. For example:

  • do you package all your js code into a single file and serve it for all requests?
  • do you conditionally load certain js depending on controller/action?
  • what tools or techniques do you use, ie: asset_packager, yui compressor, sprockets, BigPipe inspired implementation?

A bit of background: I work on a massive Rails app that is very JS heavy. Currently, all js is minified and served from a single file. This makes things very convenient as all frameworks and widgets are available everywhere. I'm beginning to question this approach is it seems a bit crazy to make all users pay the price for some js that they may never see. Littering the code with script includes seems crappy and difficult as large portions of the site deliver content via ajax.

Anyone have any advice to share?

Thanks much!

+1  A: 

First of all, try this plugin for Firefox: http://developer.yahoo.com/yslow/. It will help you determine sources of slowness, and can analyze your script usage and suggest improvements.

Also, check out this article from Yahoo on best practices for fast websites: http://developer.yahoo.com/performance/rules.html. This advice applies to all websites, not just rails.

SimpleCoder
+2  A: 

There are several trade-offs to consider:

  • If you have one big JS file then it should be cached for all your pages. But if only a few pages use JS then this isn't good.
  • If your pages don't share JS then you may want to use "as needed" loading for each page's individual JS. But you don't want too many loads since each JS fetch has its own overhead.

Notes

  • Make sure all of your JS will be cached forever on your clients. Use version numbers in the file names or urls (foo.js?123)
  • Make sure that JS files are minimized.
  • Make sure web server has gzip encoding turned on.
  • You may want to use a low-cost content delivery network for your JS such as Amazon's Cloudfront or one of their competitors.

Answers to your specific questions

Do you package all your js code into a single file and serve it for all requests?

All requests get a large file of JS that has library code and JS used on most pages. Some specific pages also get an additional JS file.

do you conditionally load certain js depending on controller/action?

Yes, for a couple of very heavy JS pages, those pages get an additional JS file. All pages get the reg JS file and it is cached/available for all pages.

what tools or techniques do you use, ie: asset_packager, yui compressor, sprockets, BigPipe inspired implementation?

  • YUI Compressor
  • S3 for serving my assets.foo.com domain
  • rake tasks to merge/minimize multiple JS source files
Larry K