A while ago I was asked to write some front-end dev best practices.

General Web Development Best Practices

Standards change over the years though, and some current practices are considered not so good anymore.
Additionally, not every developer knows about these best practices and unfortunately, over the years, bad practices have crept in.
In particular the JavaScript in the head section, the specificity in CSS styling, some style class and ID naming conventions, no use of sprites, lack of responsive media queries, lack of namespacing,… to name a few.
Still, this doesn’t mean when you add functionality, you shouldn’t keep to best practices yourself. No excuse now not to know them.

The following lists are a collection of some industry standard best practices (from Google, Mozilla, Opera, Yahoo, Nokia,…).

HTML Best Practices

  • Separation of concerns! Separate structure and content (the HTML) from presentation and behaviour.
  • Don’t use tables for layout, or spacer gifs. Use CSS to position elements on the screen. Only use tables for their intended use, tabular data, like lists.
  • Write valid HTML5, where possible. Validate your HTML! Sometimes one browser may display a page properly, while another browser may fail (because of missing closing tags for example).
  • Use HTML according to its purpose. Choose good semantic elements: headings, lists, paragraphs.
  • Use the right HTML element at the right place. For example, use <em> or <strong> in stead of <b> (which is a presentational element). Don’t use <br /> tags to create whitespace, don’t use <blockquote> for indentation purposes; use <blockquote> when actually quoting text.
  • Understand the difference between block elements and inline elements. Block elements are elements that naturally clear each line after they’re declared, spanning the whole width of the available space. Inline elements take only as much space as they need, and don’t force a new line after they’re used. Block elements shouldn’t be nested inside inline elements.
  • Keep your tag names lowercase.
  • Although not strictly necessary (in HTML5), close all HTML tags, to help readability and writing valid code. The was developed based on XHTML (which required closing all tags), but since then we moved to an HTML5 doctype.
  • Think about basic accessibility:
    • Add “for” attribute to label tags with form fields (but don’t add them when there are no form fields).
    • Add “alt” attributes to image tags and “title” attribute to links, but they should be used to increase the meaning of the associated tag!
  • Write consistently formatted code. A cleanly written and well-indented code base shows your professionalism, as well as your consideration for the other people that might need to work on your code. Remove trailing white space.
  • Avoid excessive comments. While documenting your code, the purpose is to make it easier to understand. But markup is very much self-explanatory and commenting every line of code does not make sense. If you really need to comment, always use JSP comments, not HTML comments which end up in the source code, and may have unintended consequences (for example, adding 400KB of HTML code because the JSP code was generating additional select options in a for loop, which weren’t supposed to be generated).

CSS Best Practices

  • Separate content from presentation. There should be no inline or embedded css styling in your code, as it becomes a lot harder to change the presentation afterwards without toughing the JSP. Keep all CSS external. Additionally, those external files can be cached by the client.
  • Use ID and class names that are as short as possible but as long as necessary. Keep to English.
  • Use useful, semantic naming for your IDs and class names, don’t use presentational properties as class name. Example, don’t use “red-title”, or “left-block”. What if those need to change in color, or position? Those names would no longer make sense. Use “warning” or “sidenote” for example.
  • The order that style sheets are loaded in matters. The last style sheet wins. This means you can add your own style sheet and apply your own layout/colours to the , without duplicating all existing style sheet content.
  • Use valid CSS, unless dealing with bugs (ahum IE) or proprietary syntaxes.
  • Use shorthand for padding, margin, font and others.
  • Add comments, add the entity name of the page you’re working on, like /* =RiskFilter */ for easy lookup
  • Combine elements with same styling, don’t be repetitive.
  • Reuse existing style classes!
  • Use multiple classes on a single element, don’t create a new style class just because of one single change
  • If the value of the width or height is 0, do not specify units.

JavaScript Best Practices

  • Separate content from behaviour. Don’t liter the JSP with inline JavaScript. Whenever you need to add or remove behaviour you would need to change or override the JSP. Use the addEvent() event handler (from app.js) to add Javascript events to elements in stead.

  • Use standard rather that non-standard features. Test for features, not browsers! Don’t write code specific to a certain browser.

  • Reuse the app.js library and its methods where possible.

  • Use namespacing techniques, using object literals, or the Module Pattern. Avoid global variables and function names.

  • Use array and object literals rather than more verbose declarations.

  • Don’t use eval(). It degrades performance, and can leave your application open to security issues (and will be flagged during security audits).

  • Always use var to declare variables (else they end up being global), but use commas to avoid redundancy of keywords and reduce code size.

  • Always end lines with a semi-colon (unless you know the ins and outs of Automatic Semicolon Insertion rules by heart). This prevents bugs, makes your code more readable, and is required when minimizing your code.

  • Always use curly braces, don’t leave them out. Improves readability.

  • Call things by their name — easy, short and readable variable and function names. Keep to English.

  • Comment as much as needed but not more. Preferably add JavaDoc style documentation (jsdoc) explaining functionality and members.

  • Modularize, one function per task. Keep your method lengths to a minimum.

  • DRY. If you find yourself doing the same thing in several different functions then it is a good idea to create a more generic helper function instead, and reuse that functionality where it is needed.

  • Use strict-equals === in stead of equals ==.

  • Modify invisible elements, to prevent unnecessary repaint of the screen.

  • Don’t mix your JavaScript with CSS. Use class names in stead of hardcoded style values when changing elements.

  • Think about Internationalization. Don’t hardcode date formats or error messages in your JavaScript.

  • Declare variables outside of the For statement. Cache the length of the array you iterate over.

  • Keep computation-heavy code outside loops, especially DOM manipulation.

  • Mind your commas in object literals! If the last entry in the list contains a comma, IE will throw a fit!

  • Keep DOM access to a minimum. Avoid traversing large number of DOM nodes, select a parent element first.

  • Cache frequently accessed DOM values into variables. For example:
    Don’t

    |
    document.getElementById(``'elem'``<wbr></wbr>).propertyOne = ``'value of first property'``;
    document.getElementById(``'elem'``<wbr></wbr>).propertyTwo = ``'value of second property'``;
    document.getElementById(``'elem'``<wbr></wbr>).propertyThree = ``'value of third property'``;
    | |—|

    Do:
    |
    `var elem = document.getElementById(``'elem'``);`
    `elem.propertyOne = ``'value of first property'``;`
    `elem.propertyTwo = ``'value of second property'``;`
    `elem.propertyThree = ``'value of third property'`
    | |---|
  • Embrace progressive enhancement. Always (try to) compensate for when JavaScript is disabled. Try the page out with JavaScript disabled.

  • Make sure your browser tells you about all JavaScript errors. In IE8, this used to show up in the Status bar. In IE9/10 though, it’s suppressed (an no Status bar is displayed by default). To enable on IE9/10, in Advanced settings, enable “Display a notification about every script error”, and hit F12 for the Developer console. If you don’t, JS errors may pass by unnoticed. Better yet use Firefox with the Developer Toolbar and the Firebug extensions, or Chrome with its Developer console.

References

These are some best practices. Stacks of books have been written on HTML5, CSS and JavaScript,
as well as Web Performance, Responsive Design, Grids, Accessibility, Web App Security,…

Books

JavaScript: The Good Parts (Douglas Crockford)
Professional JavaScript For Web Developers (Nicholas Zakas)
JavaScript: The Definitive Guide (David Flanagan)
Effective JavaScript (David Herman)

HTML & CSS: The Good Parts (Ben Henick)
CSS: The Definitive Guide (Eic Meyer)

Websites, blogs

Tools

When using Firefox, use Firebug, and install the Web Developer Toolbar extension.
When using Chrome, hit F12 for its developer tools.
These developer tools help you to debug screen issues, play around with CSS (changing values on the fly and see their impact), step through JavaScript code, write out JavaScript values to a console (in stead of relying on alert() calls), validate the generated HTML, work around maxlength attributes to test validation, enable read-only form fields,…

Microsoft provided VMs to test IE7/8/9/10: http://www.modern.ie/virtualization-tools

My week in pictures 18 Aug 2013 #weekinpix
Older post

My week in pictures 18 Aug 2013 #weekinpix

](https://halans.com/orig-content/uploads/2013/08/Image.jpg)

Newer post

Australian Online Retail

<rant> So I bought something on JBhifi.com.au. Yeah right, I know. I ordered a GoPro accessory, for $19.99, which was available for pickup at the North …

Australian Online Retail