NOTE: I have now created a jQuery plugin which is my attempt of a solution to this issue. I am sure that it could be improved and i\'ve probably overlooked lots of use c
Having less javascript files minimizes the number of requests sent to the server and caching the files makes the second and third pages load faster. Usually, I think about the likelihood of some parts of a js file will be needed in the following pages (and not just the current page). This makes me categorize my js code into two types: code that goes in my "main.js", and even if not used, it is going to be downloaded by the client (but not necessarily executed, I will explain), and the second category of code goes in separate files. You could actually create multiple files grouped by probability. This depends on the details of your project. If it's a large scale project, running some statistical analysis on user behavior might reveal interesting ways of grouping js code. Now that the code has been downloaded to the client, we do not want to execute all of it. What you should do is have different layouts or pages. Place a partial in the layout or page. Inside the partial set a javascript variable. Retrieve the javascript variable in the javascript code and determine whether you want to execute some code or not.
i.e:
Create partial "_stats.html.erb", place this code in it:
Place the partial in the pages you would like to collect statistics: show.html.erb
<%= render "_stats", :collect_statistics => false %>
Now in your js file, do the following:
$(document).load( function() {
if (typeof collect_statistics != "undefined" && collect_statistics) {
// place code here
}
});
I hope this helps!