Monday, April 06, 2009

High Quality Javascript

Writing good javascript is still more art than science, but there are a growing number of tools out there to help those who are less artsy. I have tried to compile the ones that I use and a few tips which I think are helpful.

jQuery (http://jquery.com/) - a great javascript framework built for developers
If you are still writing javascript without using a framework like jQuery then you are punishing yourself. Stop that! This framework makes javascript work like it probably should have anyway and it is very reliable and widely used. It helps protect you from browser incompatibilities and makes ajax very easy. There are a large number of addons and extensions which provide flashy widgets and things to make your UI look snazzy.

JSLint (http://www.jslint.com/) - this website / tool is similar to findbugs for java and helps with correctness and valid code practices (NOTE: Can enable JSlint in Aptana Studio, see tips below)
JSLint is a JavaScript program that looks for problems in JavaScript programs. Just paste your javascript file into the box and click JSLint. I use the following options (good starting point if you are not sure what to use):
Assume a browser, Disallow undefined variables, Disallow leading _ in identifiers, and Disallow == and !=
You should strive to have no errors indicated. I recommend you avoid the Strict white space and Require parens around immediate invocations options as these are more likely to cause frustration than be helpful. JSLint will also provide you with a list of all functions, members, and Globals in your code which is helpful as a reference.

jqUnit (http://code.google.com/p/jqunit/) - a test writing framework (like jUnit for java)
This is a test framework which allows a developer to write tests which exercise and validate their javascript code. It is compatible with JSUnit but has special handling for jQuery and since you are using jQuery anyway you may as well get the benefits. The tests run in the browser and normally are accessed by loading a page (e.g project/test.html). I won't go into the reasons why you should always have unit tests but if you want high quality code then they are not optional. This will have a huge impact on the reliability and change tolerance of your code and since JS code in general tends to change a lot this is critical.

Fluid Infusion (http://fluidproject.org/products/fluid-infusion/) - framework for accessible javascript
The fluid project is trying to ensure that javascript enabled pages are accessible to everyone. They have a framework which includes widgets which are specially designed to be accessible and also have a lot of documentation for developers.

Aptana Studio (http://www.aptana.com/studio) - IDE for javascript, HTML, DOM, CSS
This is an eclipse based IDE for the web. It provides code completion, formatting, validation, and the things you might expect to get from an IDE. This makes writing javascript a heck of a lot easier and it looks better than textedit/notepad. I just use the eclipse plugin rather than the full product now and if you are web designer or just trying it out then the full option is probably best (as it seems it does not uninstall from eclipse cleanly).

General Tips:
  • Always namespace your javascript functions and vars - http://www.dustindiaz.com/namespace-your-javascript/
  • Write unobtrusive javascript (this basically means avoid writing code in your html except for a few lines at the bottom to run scripts and pass in values as needed) - http://www.onlinetools.org/articles/unobtrusivejavascript/
  • Always use var in front of variables, if you don't they will become globals and when you are namespacing (which you should be) this is considering leaking
  • Declare globals at the top of your JS file in a comment like so:
    /*global jQuery, myGlobal */
  • Always refer to globally used variables at the top of your script so it will fail if the global is missing. This will make JSLint happy and keeps things from appearing to work when globals are not available. Example:
    var $ = $ || function() { throw "JQuery undefined"; };
  • Check to make sure you found something when you use jQuery selectors (if you always except to find something). This protects you from thinking you have actually found something based on an id when there is nothing by that id available. Example:
    var adhocArea = $("#"+adhocAreaId);
    if (adhocArea.length > 0) {
    // do something
    } else {
    throw "failed to find thing with id: "+
    adhocAreaId;
    }
  • Use script blocks to initialize javascript when the DOM it is working with has loaded rather than always (ever?) using onLoad. This will cause the javascript to start quicker on slow loading pages and avoid ugly issues like resetting selections made by the user or clearing fields which had loaded before the whole page loaded and the onLoad executed. For example, if you are adding a simple numeric validator to a field, you should place the script tag to load the JS (from a namespaced variable in a separate file) after the form. This way the script executes as soon as the DOM it will act on is loaded.
  • Be familiar the concept of closures in javascript - http://www.jibbering.com/faq/faq_notes/closures.html
  • Quirksmode is a good reference for javascript cross browser compatibility
  • Enable JSLint validator in Aptana Studio: Preferences -> Aptana -> Editors -> Javascript -> Validation -> Check JSLint Javascript Validator
It is probably a good idea to glance at AJAXian every once in awhile as well.

2 comments:

Unknown said...

In case you install Aptana Studio, and you want to uninstall it for some reason, you are out of luck. There is no clean way to do this.

AZ said...

Good point on the Aptana stuff. I normally would recommend installing Aptana Studio as a standalone rather than putting it inside an existing eclipse installation. Definitely do that if you are just previewing it. I will update the post to make this more clear.