Topic: how do you organize javascript code in your rails project?

how do you organize javascript code in your rails project?

Here is how I organize javascript code in my current project: I include common javascript files on the bottom of a layout file and yield :javascript content. It looks like this:

= include_javascripts :common
= yield :javascript

Then in every page rendered, I put the related javascript code at the bottom of the page, it looks like this:

-content_for :javascript :javascript //code goes here…

The question is should I put the code in to a separate javascript file or it is okay to put javascript with the html content it manipulates? Any advantages and disadvantages?

In addition, there could be some javascript code that manipulate html content in partials, how do you organize them?

In summary, what is your best practice for organizing javascript code in your rails project(especially there are a lot of javascript code)?


Re: how do you organize javascript code in your rails project?

Putting all the common functions in a separate file has performance benefits. Your browser 'sees' dynamic content generated by your Rails app as just another HTML file, but because it's dynamic it can't be cached in the browser cache. By moving common JS functions to a common file (or files) the browser will issue separate GET requests to download them. But once he has downloaded them once, they are in the browser cache and won't be re-fetched until they expire, which can save you some network bandwidth and make your application seem more responsive.

MS SharePoint has some pretty chunky JS to support the UI, and it uses this method to ensure it only gets downloaded once.

You can also consider compressing the (separate) .js file; most browsers are smart enough to cope with this these days. The benefits are:

  • You only have to compress it once on the server

  • It uses less of your bandwidth because the compressed file is much smaller

  • Each client will only download it once

  • The decompress occurs on the client, i.e. on someone else's hardware, not yours

You can do the same with stylesheet files, if they are large.

There is a useful IE add-in called Fiddler which is free to download. Aside from the fact that it only works with IE, it will show you the files that get downloaded for each page, and also has a 'what if' capability for compression. I'm assuming that anyone making a Rails app will need to have an instance of IE running somewhere, even if it's only for user testing smile
