If you worked on an enterprise app before you probably know that JavaScript files (or style sheets) quickly grow in size and in number. The loose nature of JavaScript is inherently problematic and developers haphazardly take advantage of it. For example, letting developers decide whether JavaScripts are inline, external or page-wide could easily bog down a project’s code base. I have been burned repeatedly by letting developers run amok with their own JavaScript conventions. It starts unsuspectingly harmless. As the project grows, code begins to rot. Debugging becomes painfully hard. Bugs crop up all over the project and the team’s capability to troubleshoot problem quickly dives. The last part is the most terrifying. You could easily lose countless hours just for tracing bugs.
To mitigate this, I have written a JavaScript guidelines and conventions(among others) for my team and enforced it. I also religiously monitor them during code review. This two-pronged approach is necessary because without the other, it is very challenging to make developers create clean JavaScript code. I don’t intend to paste the entire thing here but below are the important details:
Go Unobtrusive JavaScript all the way—I cannot stress this enough. Unobtrusive JavaScript enforces a clean separation between HTML page and JavaScript. This is really valuable during troubleshooting and modification.
One JavaScript file per view (HTML)—this may sound a little obsessive, and it is, but it pays off in the long run. This strategy encapsulates the functionality of the page in one file and isolates possible problem from the other. The performance hit this entails should be negligible for enterprise applications.
One JavaScript file for common codes—be vigilant as this will be abused. A good rule of the thumb here is to count the number of page that a code affects. If it does not reach a certain number, do not allow developers to put it in the file.
Define a file naming convention—this Stackoverflow discussion enumerates some of the common JavaScript file naming conventions. Most of the suggestions are superfluous for an enterprise project but you can definitely take something away from the discussion.
We use the format [module-name].[view-name].js. It’s clear and straightforward. Enterprise apps are typically comprised of modules so this way they are grouped together. Avoid using folders to group files as this impedes locating files.