Contents

Accessibility

What's Up, DOCTYPE?

The absence of a DOCTYPE is a crime punishable by death. You may have relied on the following DOCTYPE in the past, but it's important to know that this is now being superseded by a leaner and meaner snippet.

Ideally, the HTML5 DOCTYPE should be used. It's supported in all modern browsers, and throws IE6 and IE7 into standards mode. Source.

Write Valid Semantic Markup

Writing websites with clean, semantic HTML is something we wish we could always do. Sometimes we find ourselves limited by the way pages were setup by our predecessors, or sometimes we're coding an HTML email. The validity of the HTML should never be compromised, even if to solve a browser specific bug.

Headings should be heirarchically created from <h1> onwards, paragraphs should always be in <p> tags and so on and so forth. If you write semantic HTML, the resultant page will be cleaner, lighter and easily parsed by search engine spiders. This is one of the simplest SEO fixes you can undertake.

Which do you think looks cleaner, this?:

Or this?

Images Need ‘Alt’ Text

The <img> tag requires alt text to both validate and meet accessibility guidelines. The text in the alt attribute should be descriptive of what the image shows, or is trying to achieve, unless of course the image is not critical.

If the image is of a list bullet or other trivial icons, it is recommended to simply leave the alt attribute empty, but still present. A screenreader will then ignore it, as opposed to having to read out "bullet" 20 times.

Use Tables for Tabular Data Only

Tables should only ever be used for the presentation of tabular data. The only exception is when composing HTML email, in which a table is almost the only thing supported by soul crushing email clients.

For accessibility, table headers should always be presented using <th> elements. Remember to also set cellpadding, cellspacing and border values to 0 as these are more consistently controlled by CSS.

Use jQuery

jQuery is constructed to look and behave as close to identical as possible on different browsers.

JavaScript

Whitespacing & Formatting

Any discussion about formatting, whitespacing and the placement of braces is going to be hotly debated. I guess the simplest rule is that, unless you're willing to completely format a whole document, respect and maintain the formatting of an existing document. That means: see same-line braces throughout a JS file, continue to write code with same-line braces. Your code should fail the code review process if it doesn't maintain consistency with the rest of the document.

Consistent formatting makes code more readable, and also means the code can be easily modified with find and replace commands. The coding habits we have picked up are thankfully very similar to what jQuery officially encourages. There are a few minor discrepencies, but again, these are personal issues or things that we think cannot be maintained. Further Reading

Character Spacing

Same Line Braces

Use same line braces in return statements to avoid unintentional automatic semicolon insertion and everywhere for consistency and legibility.

Always Using Braces

String Handling

Strings should always use double quotes. Some people are very fond of their C style strings (single quotes), but this leads to conflicting styles within a script. C style string handling dictates that empty and single character strings should be wrapped in single quotations, while phrases and words should be wrapped in double quotations.

The lone exemption occurs when quoting HTML markup. This is acceptable:

Commenting

The requirement to comment code obsessively was pioneered by managers, team leaders and other people that interact with code infrequently. It is sought merely as a check box for an employee's KPIs, and provides little return for the time spent doing so.

If a best-practice oriented developer follows the guidelines established in this document, their code should become so readable and obvious that the need to comment what it is doing is embarassingly redundant. Consider the following example. In this: booleans are posed as questions, and functions are named intuitively.

Commenting, in this scenario at least, is completely unnecessary. Here's a couple other examples of intuitive boolean naming:

SITUATIONS WHERE COMMENTING IS IMPORTANT

Some parts of a project will never be easy to scan and understand. Consider a complicated regular expression, or a math function calculating angles or switching between degrees and radians. Without the comment above, beginner and intermediate readers will be fairly clueless to the scripts' meaning.

Always Use === Comparison

The use of the == equality operator allows for frustrating bugs to slip through almost undetected. It allows for weak typing that is best explained by JavaScript Garden. The use of the strict equality operator === does not run type coercion and therefore strictly evaluates the difference between two objects. Again, consult JavaScript Garden for more information

The Exception

Double equals comparison is allowed when comparing to null, because it will detect both null or undefined properties. If you don't fully understand this, I still suggest you use triple equals.

Always Specify the Second ‘radix’ Parameter When Using .parseInt()

When parsing a string to an integer, it is considered good practice to specify the second 'radix' parameter - which determines to what base the string should be converted to. The default setting will trigger a radix of 16 whenever the string is lead by a 0. Most beginner and intermediate users are only ever going to be using a radix of 10. Thanks to João Moreno for logging the correction.

Avoid Comparing to true and false

Direct comparison to the values of true and false is unnecessary. Sometimes it might be good for clarity, but it's just extra code.

Avoid Polluting the Global Namespace

An over-reliance on global variables is something all of us, myself especially, are guilty of. Arguments as to why globals are bad are fairly straight forward: the chance of script and variable conflicts is increased, and both the source file and the namespace itself become littered with countless ambiguously named variables.

Douglas Crockford believes that the quality of a JavaScript application can be assessed by the number of global variables it uses; the less the better. Given that not everything can be a local (but let's be honest, that one you're thinking about right now, it can, don't be lazy) you need to find a way of structuring your variables to prevent clashes and minimise the bloat. The easiest way is to employ a single variable or a minimal amount of modules on which the variables are set. Crockford mentions that YUI uses a single global, YAHOO. He discusses this in more detail in his blog post "Global Domination".

Considering that, in the case of small web apps, globals are generally used to store application-wide settings: it's generally better to namespace your project or settings as objects.

But if we're avoiding globals to reduce the chance of conflicts, isn't standardising the namespaces to be the same going to increase chance of one app's settings overwriting anothers? Well, it would make sense. It is instead suggested that you namespace your globals to your own specific app name, or reassign your namespace much in the same way that jQuery uses $.noConflict() mode.

Camel Case Variables

The camel casing (or camelCasing) of JavaScript variables is accepted as the standard in most coding environments. The only exception that was raised in the comment section is the use of uppercase and underscores to denote contants.

Rosy Variables

Let's define variable conventions used in Rosy to represent classes, variables, and methods.

Rosy Class Namespace

Use the extension namespace to imply inheritance. Let's take a look at an example:

Camel Case Class Names, hyphenate file names

Example: TwitterPoll is a Module on your blog. Place it in the correct namespace and camel case it like so LOLBlog.Module.TwitterPoll. Save it in a file like so lolblog/module/twitter-poll.js. Boo-ya, organized.

jQuery Variables

Caching your jQuery $(selectors) is considered most awesome.

You'll notice that $articles has...well.. a $ in front of it. That's to ensure that you know the variable is a jQuery object! Legibility convention....holla!

Readable Milliseconds

A handy way of writing milliseconds in a readable format.

Loop Performance - Cache Array Length

Looping is arguably the most important part of JavaScript performance to get right. Shave a millisecond or two off inside of a loop, potentially gain seconds overall. One such way is to cache the length of an array so it doesnt have to be calculated every time the loop is iterated through.

The Exception

If you're looping through an array to find an remove a particular item, this will alter the array length. Any time you change the array length by either adding or removing items from inside the loop, you will get yourself into trouble. Consider either re-setting the length or avoid caching it for this particular situation

Loop Performance - Use ‘break;’ & ‘continue;’

The ability to step over and out of loops is really useful in avoiding costly loop cycles.

If you're looking for something inside of a loop, what do you do once you find it? Say the condition you're looking for is matched halfway through a 1000 item loop. Do you execute whatever you intend to do, and allow the loop to continue to iterate over the remaining 500 items, knowing that there's no chance it will hit an if statement? Nope! You break out of your loop, literally!

Another problem is skipping over a particular iteration and then continuing on with the loop. While things like odds and evens are better managed by replacing i++ with i + 2, some conditions need to be specifically listened for, to then trigger the skip. Anything that prevent's running through an entire iteration is pretty handy.

Don't Send Too Many Function Parameters

This is a pretty bad idea, more for readability than anything:

It's a much better idea to construct an object before-hand or to pass the object inline

CanIHaz Boolean?

Booleans should be named with the prefixes of is, can or has.

Feature Sniff, Don't Browser Sniff

Does the client's browser support geolocation? Does the client's browser support web workers? HTML5 video? HTML5 audio? The answer used to be:

But things are rapidly changing. The latest version of IE is almost a modern browser, but as usual it's making front end development a pain. Earlier versions of IE were generally as equally sucky as their predecessors, so it enabled lazy JavaScript developers to simply detect if (ie) and execute some proprietary Microsoft slops syntax. Now IE9 has done away with these functions, but that old if (ie) chestnut is throwing a spanner in the works.

So what if you could detect support for individual features without sniffing the (unreliable and cloakable) user-agent?

If you answered "that would be ghetto", then you are correct.

In steps Modernizr, a JavaScript library developed in part by industry dream-boat Paul Irish. With wide adoption, tiny file-size and plenty of documentation: implementing it is a no-brainer. It creates a Modernizr object that contains the results of its detection tests, so checking feature support is as simple as the following:

jQuery Specific

‘.stop()’ Collaborate & Listen

Binding jQuery animations to mouse events is a key part of modern web-based user interaction. It's also something that you see done poorly on even the most famous of web sites. This article provides a straight forward example of built up animations and demonstrates how visually jarring they can be. Thankfully it's easily fixed with a single function prefix or a parameter added to $.animate calls.

When using $.animate, queue: false can be added to the parameters to prevent chaining. Animation shortcuts such as $.fadeIn or $.slideDown do not take queue settings. Instead you have to pre-empt these animations with the $.stop method of pausing currently executing animations. Certain scenarios require the animation to stop dead in its tracks, or to jump to the end of the transition. It is recommended you familiarise yourself with the documentation of the parameters clearQueue and jumpToEnd, because god knows I can't help you there.

Tangentially, I find it odd that what I can only assume is an American authored library uses such a profoundly British word as queue.

Optimise Your Selectors

jQuery is pretty chill. It can do pretty much everything but make you coffee, and I hear that's in the roadmap for 2.0. One thing you have to be careful about is abusing the power that is the sizzleJS selector engine. There are two strategies to overcome this: caching the selector results and using efficient selectors.

Caching Selector Results

Do a costly DOM query every time you want to change something, or store a reference to the element? Pretty clear choice.

This is better:


Using Efficient Selectors

So jQuery/sizzleJS can use CSS3 selectors like a boss, but what's the real cost? Behind the scenes the browser is hopefully using document.querySelector(), but there's also a fair chance it will be breaking down your selector string and querying the DOM manually.

A ‘for’ Loop is Always Quicker Than a ‘each()’ Loop

No matter what happens in the next few years of browser development, a native for loop will always be quicker than a jQuery $.each() loop. When you think of what jQuery really is (a library wrapped around native JS functions) you begin to realise that the native underlying JavaScript is always going to be quicker. It's a tradeoff of run speed versus authoring speed.

It is vital that a native for loop is always used for performance critical functions that could fire potentially hundreds of times per second. Examples include:

CSS

SASS + Compass

Use SASS to compile your CSS files.

Sass is an extension of CSS3, adding nested rules, variables, mixins, selector inheritance, and more. It’s translated to well-formatted, standard CSS using the command line tool or a web-framework plugin.

Sass has two syntaxes. The new main syntax (as of Sass 3) is known as “SCSS” (for “Sassy CSS”), and is a superset of CSS3’s syntax. This means that every valid CSS3 stylesheet is valid SCSS as well. SCSS files use the extension .scss.

The second, older syntax is known as the indented syntax (or just “Sass”). It's considered too different from CSS and should not be used for development.

Compiled CSS

Never edit a compiled style sheet directly. It will be overwritten once the master .scss file has been modified and saved. If there is any confusion on whether the style sheet is compiled, assume that it is.

Whitespacing

Whitespacing of CSS can be difficult as we chop and change between single and multi line CSS arguments. I'm not going to get into that.

Proper Spacing

Same Line Braces

Indenting Child Elements

SASS provides support for indentation. Always indent child elements to avoid DRY.

CSS Shorthand

Grouping Properties

Grouping properties together is one of the single most effective methods to greatly reduce the size of a CSS file. It's important to understand how properties are ordered (clockwise - top, right, bottom, left) and how they can be further shortened (top and bottom, left and right).

From 0px to Hero

Assigning a unit type to a property value of zero is redundant. It is not important to know whether an element should be 0px from the left or 0 elephants from the left, just that it's bang on the left.

Commenting Blocks

Commenting large blocks of CSS is a great way of keeping track of multiple style areas within the one stylesheet. Obviously it works better with single line CSS styles, but the effect is not entirely lost on multi-line either. The use of dashes versus equals versus underscores are all up the individual, but this is how I like to manage my stylesheets.

Clearing Floats

Clearing a <div> used to mean extra DOM, because it involved adding an extra clearer element. The better way is to set a specific width on the parent element (it doesn't work if it is "auto") and an overflow value of either auto or hidden. "Hidden" obviously degrades better, but there are some IE compatibility versions where auto works better.

The HTML:

The CSS:

Contributors have also brough the latest clearfix to my attention. The micro clear-fix is considered stable and cross browser compliant enough to make it to the latest HTML5 boiler plate release. I highly recommend you check it out. Although I am not a massive fan of browser-specific CSS and pseudo elements such as :after, the micro clearfix is definitely more robust. It also prevents top margins from collapsing which is an absolute life saver.

Feature Sniff, Don't Browser Sniff

In the earlier discusison of JavaScript feature detection, applying properties if a browser is any version of IE is increasingly problematic. Man-of-steel Paul Irish pioneered the use of IE version sniffing to address this problem, but Modernizr has since come to the rescue. Modernizr places classes on the root <html> element specifying whether features are supported. Bleeding edge styles can then easily cascade from (or be removed from) these classes.

You're Not !important

A reliance upon the !important tag is a dangerous thing. The cases that warrant its use are rare and specific. They revolve around the necessity to override another stylesheet which you do not have access or permission to edit. Another scenario is hard coding an element's styles to prevent inline JavaScript styles from taking precedence. Instead !important is used as a lazy shortcut to set the priority of your style over another, causing headaches further down the line.

The use of the !important tag can be mostly avoided via the better understanding of CSS selector precedence, and how to better target elements. The more specific the selector, the more likely it will be accepted as the applicable style. The following example from vanseodesign demonstrates the specificity at work.

Their article on style precedence does a better job explaining inheritence than I ever could, so please give it a go.

Aggressive Degradation

It's worth noting that this is a personal opinion, and best suited to very specific situations. The stance of aggressive degradation will not be well received in large commercial projects or enterprise solutions relying upon older browsers.

Aggressive degradation dictates that if a particular (older) browser cannot render a certain effect, it should simply be omitted. A CSS3 button is a good example. Effects such as border-radius, box-shadow, text-shadow and gradients will be displayed in cutting edge browsers. A graceful fallback of a .PNG would be provided for slightly older browsers, and the most graceful of all solutions would include a PNG-Fix for IE6 or the use of filter arguments to replicate gradients and shadows. However, aggressive degradation in this situation instructs you to neglect the older browsers and present them with a flat, satisfactory object.

Put simply, aggressive degradation boils down to: if your browser can't render a gradient or a box shadow, tough luck.

While not ideal for every situation, it ensures the timely delivery of projects and that the root product is still usable and not reliant on (validation breaking) hacks.

CSS3 & HTML5

Feature Sniff with Modernizr

I think I've gone on enough about this already. Use Modernizr to detect the availability of specific HTML5 and CSS3 features.

@font-face Use and Abuse

Before you consider embedding a custom font, is important that you inspect the EULA and check if web embedding is allowed. Foundries are understandably reluctant to allow designers and developers the ability to place font files directly on a server which can then be copied by a savvy end user. Particular foundries also prohibit the embedding of particular file types, such as .TTF and .OTF.

If, after careful consideration, you believe the desired font is web embeddable: head on over to the Font Squirrel @font-face Generator. It utilises Fontspring's bulletproof @font-face structure and automatically generates all the required file formats.

Degradation

Thankfully browser handling of unsupported HTML5 and CSS3 is already that of a graceful nature. New additions to the list of <input /> types such as "email", "search" etc. will generally degrade to normal <input type="text" /> when not natively supported. Similarly, CSS3 properties that aren't supported will simply not appear. Responsive layouts controlled by height and width media queries are simply not applied.

Subtle CSS3 effects should be employed as a reward for users who run a modern browser.

The resources section below includes a few libraries to help normalise HTML5 and CSS3 functionality across a range of older browsers.

Resources

Support and Suggestions

The following resources are vital for the standardisation of code and interaction in a modern web page. They ensure that CSS3 and HTML5 features are made accessible across a range of browsers that previously lacked support.

Support and Suggestions

This document was prepared by Tait Brown (@taitems).

Questions, corrections and suggestions can be lodged on the GitHub repository for this page. You can also fork your own branch and add your own company/product specific guidelines.