This post is based on code that was written over a weekend. Code quality may vary.
Last weekend I created a simple webpage called metadash that provides a list of links that are stored in a cookie. Nothing too remarkable. But it does seem like a good place to extract and discuss some common programming idioms and best practices.
HTML — the skeleton
Most of my projects start off with a bit of HTML. In general,
I follow the recommendation to put styles up top right before
</body>. This allows
the browser layout engine to start parsing the stylesheets before the
DOM elements to which the styles apply are loaded. Similarly,
the scripts typically operate on the DOM and wait for it to load, so they
might as well be loaded closer to the end when the DOM will be ready.
So overall, the HTML looks like:
It's generally a good idea to declare a
charsetfor your documents. If you don't know anything about Unicode, read this.
<script> tags are fine towards the bottom of the document, some
need to run right away before the DOM is loaded—like Google Analytics.
I make two improvements over the loading code Google provides:
Setting up the
_gaqarray directly. I do this because I know I'm not loading the same script more than once.
Other scripts that belong in
<head> are ones that operate on stylesheets
The main application HTML is in the middle of the
CSS — the skin
metadash is not the prettiest application in the world, but I wanted to include rearranging the list which required jQuery UI— which is most of the CSS.
Instead of reproducing the entire CSS here are a few interesting snippets.
display: inline-block;is possibly the best finds I've had in CSS. It allows
<li>) to behave like block-level elements (e.g.,
<div>) so you can set their
width—without creating a new line.
Until recently, I feel like vertical alignment never worked the way I expected. (I'm still annoyed that I cannot align text vertically in a
<div>without crazy incantations.)
The trick here is that the function is defined and then immediately called without being assigned to a name (hence, anonymous). The result is that any definitions that are exposed to the outside world are thereby invisible to everything outside the defined scope.
The result is a small little personal dashboard that is entirely cookie-based.
Best Practices for Speeding Up Your Web Site at Yahoo! Developer Network for a list of performance enhancing techniques.
The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) at Joel on Software for a primer on Unicode.