I am in the process of converting an internal application to use more Ajax via jQuery. I am moving away from the standard code behind of the current ASP.NET application and incorporating JavaScript methods that are going to run client side. My concern is what is the best method for allowing this application to stay maintainable for those who come behind me.
I would suggest putting as much of the javascript code as you can into external script files, to add some modularity. But beyond that, comments and keeping the code and markup as clean as possible are the best that can be done in any programming project, regardless of language.
Create a script that runs during your build that removes all comments from javascript.
Then comment liberally, and encourage everyone else to also, safe with the knowledge that comments won't make it into production.
I would say that applying the same sort of OOP principles to your javascript that you apply to server-side code is one of the best ways to enhance maintainability. Instead of global functions, think about creating classes that encapsulate your javascript methods and data. Use javascript unit testing frameworks to test this code to make sure that it is robust.
Also, if you can, try to make a bit of an object-oriented design if you can. I was once on a project that involved a lot of jQuery/Javascript, and it did not have an object-oriented design, which made it difficult for us to develop and maintain it for a while. Over time, we actually ended up rewriting parts of it to make it better.
So my best advice is to think ahead, comment (like others have said), and make sure that you code your Javascript the same way you'd code anything else (as in, follow all the good design principles that you'd use on a server-side language.)
Run JSLint as part of your build and make sure that if it doesn't pass, it fails your build.
Ensuring that your JS is valid is not a key to maintainability but it will flesh out some browser issues that might have otherwise squeaked by.
If possible, start writing unit tests using a framework like Rhinounit, JSUnit or QUnit.
I've found that build scripts are the key to success in maintainable Javascript. Essentially in order to have something fast and concise on the final page you need a script to make that maintainable in development.
If you use a build process you can break your JS into files based on the functionality. You can use the debug versions of libraries during development, and leave glorious code comments smattered around your code with impunity.
A build script should:
- Lint all your code
- Strip comments
- Concatenate the files together
- Minify/Obfuscate/Compress the code
- Version files for deployment
- Push the version files to the server ready to be "turned on" in production
This leaves you to work on files that make logical sense and it to tidy up after you for production.