I am using rails and I have lot of javascript functions,I don't want to put them in application.js. Is it fine to move them to different js files based on the layouts ? so that the each time when I load, it will not load all of them. is there any other best practice is available for these kind of issues.
2 Answers
It seems to me you want to write your own bootstraper. Yes, this is a good idea (although it has nothing to do with rails). For example using jQuery function $.getScript() you can dynamically load only those scripts you need (of course you'll need some additional scripting to make this process automatic).
Although there are two schools: one which tends to compress as much data as it can into one big file (together with browser caching it is very nice way) and the other with bootstrapers - loading only those scripts you actually need.
On the other hand, if your scripts are not as big as (for example) jQuery itself, then it really doesn't matter, imho.
Comments
In general we follow the following rule,
- If the code is used by many controller views, put it in the application.js
- If the code is specific to a particular controller view, create a js file for that controller and put it in that. It would be easy to identify if you follow a naming convention for the js file. For a article controller, create a js as article.js
Talking in terms of performance, in rails 3.1 we have asset pipeline that compresses and packages js files. Prior to that we have many tools available that compresses and packages the js files. Example asset packager