SV Code Guide
Standards for developing flexible, durable, and sustainable HTML, CSS and JavaScript.
Golden rule
Enforce these, or your own, agreed upon guidelines at all times. Small or large, call out what's incorrect.
Every line of code should appear to be written by a single person, no matter the number of contributors.
Syntax
- Use hard tabs with four spaces.
- Nested elements should be indented once (1 tab).
- Always use double quotes, never single quotes, on attributes.
- Don't include a trailing slash in self-closing elements—the HTML5 spec says they're optional.
- Don’t omit optional closing tags (e.g.
</li>
or</body>
).
HTML5 doctype
Enforce standards mode and more consistent rendering in every browser possible with this simple doctype at the beginning of every HTML page.
Language attribute
From the HTML5 spec:
Authors are encouraged to specify a lang attribute on the root html element, giving the document's language. This aids speech synthesis tools to determine what pronunciations to use, translation tools to determine what rules to use, and so forth.
Read more about the lang
attribute in the spec.
Head to Sitepoint for a list of language codes.
IE compatibility mode
Internet Explorer supports the use of a document compatibility <meta>
tag to specify what version of IE the page should be rendered as. Unless circumstances require otherwise, it's most useful to instruct IE to use the latest supported mode with edge mode.
For more information, read this awesome Stack Overflow article.
Character encoding
Quickly and easily ensure proper rendering of your content by declaring an explicit character encoding. When doing so, you may avoid using character entities in your HTML, provided their encoding matches that of the document (generally UTF-8).
CSS and JavaScript includes
Per HTML5 spec, typically there is no need to specify a type
when including CSS and JavaScript files as text/css
and text/javascript
are their respective defaults.
HTML5 spec links
Attribute order
HTML attributes should come in this general order for easier reading of code.
class
,id
,name
src
,for
,type
,href
,value
title
,alt
role
,aria-*
data-*
Classes make for great reusable components, so they come first. Ids are more specific and should be used sparingly (e.g., for in-page bookmarks), so they come second.
Boolean attributes
A boolean attribute is one that needs no declared value. XHTML required you to declare a value, but HTML5 has no such requirement.
For further reading, consult the WhatWG section on boolean attributes:
The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
If you must include the attribute's value, and you don't need to, follow this WhatWG guideline:
If the attribute is present, its value must either be the empty string or [...] the attribute's canonical name, with no leading or trailing whitespace.
In short, don't add a value.
Reducing markup
Whenever possible, avoid superfluous parent elements when writing HTML. Many times this requires iteration and refactoring, but produces less HTML. Take the following example:
Syntax
- Use hard tabs with four spaces.
- When grouping selectors, keep individual selectors to a single line.
- Include one space before the opening brace of declaration blocks for legibility.
- Place closing braces of declaration blocks on a new line.
- Include one space after
:
for each declaration. - Each declaration should appear on its own line for more accurate error reporting.
- End all declarations with a semi-colon. The last declaration's is optional, but your code is more error prone without it.
- Comma-separated property values should include a space after each comma (e.g.,
box-shadow
). - Always prefix property values or color parameters with a leading zero (e.g.,
0.5
instead of.5
and-0.5px
instead of-.5px
). - Lowercase all hex values, e.g.,
#fff
. Lowercase letters are much easier to discern when scanning a document as they tend to have more unique shapes. - Use shorthand hex values where available, e.g.,
#fff
instead of#ffffff
. - Quote attribute values in selectors, e.g.,
input[type="text"]
. They’re only optional in some cases, and it’s a good practice for consistency. - Avoid specifying units for zero values, e.g.,
margin: 0;
instead ofmargin: 0px;
.
Questions on the terms used here? See the syntax section of the Cascading Style Sheets article on Wikipedia.
Declaration order
Related property declarations should be grouped together following the order:
- Positioning
- Box model
- Typographic
- Visual
Positioning comes first because it can remove an element from the normal flow of the document and override box model related styles. The box model comes next as it dictates a component's dimensions and placement.
Everything else takes place inside the component or without impacting the previous two sections, and thus they come last.
For a complete list of properties and their order, please see Recess.
Single declarations
In instances where a rule set includes only one declaration, consider removing line breaks for readability and faster editing. Any rule set with multiple declarations should be split to separate lines.
The key factor here is error detection—e.g., a CSS validator stating you have a syntax error on Line 183. With a single declaration, there's no missing it. With multiple declarations, separate lines is a must for your sanity.
Media query placement
Place media queries as close to their relevant rule sets whenever possible. Don't bundle them all in a separate stylesheet or at the end of the document. Doing so only makes it easier for folks to miss them in the future. Here's a typical setup.
Prefixed properties
When using vendor prefixed properties, indent each property such that the declaration's value lines up vertically for easy multi-line editing.
In Sublime Text 2, use Selection → Add Previous Line (ctrl + alt + ↑) and Selection → Add Next Line (ctrl + alt + ↓). In Atom, user Selections → Add Selection Above (alt + ctrl + ↑) and Selection → Add Selection Below (alt + ctrl + ↓).
Shorthand notation
Strive to limit use of shorthand declarations to instances where you must explicitly set all the available values. Common overused shorthand properties include:
padding
margin
font
background
border
border-radius
Often times we don't need to set all the values a shorthand property represents. For example, HTML headings only set top and bottom margin, so when necessary, only override those two values. Excessive use of shorthand properties often leads to sloppier code with unnecessary overrides and unintended side effects.
The Mozilla Developer Network has a great article on shorthand properties for those unfamiliar with notation and behavior.
Comments
Code is written and maintained by people. Ensure your code is descriptive, well commented, and approachable by others. Great code comments convey context or purpose. Do not simply reiterate a component or class name.
Be sure to write in complete sentences for larger comments and succinct phrases for general notes.
Class names
- Keep classes lowercase and use dashes (not underscores or camelCase). Dashes serve as natural breaks in related class (e.g.,
.btn
and.btn-danger
). - Avoid excessive and arbitrary shorthand notation.
.btn
is useful for button, but.s
doesn't mean anything. - Keep classes as short and succinct as possible.
- Use meaningful names; use structural or purposeful names over presentational.
- Prefix classes based on the closest parent or base class.
It's also useful to apply many of these same rules when creating Sass and Less variable names.
Selectors
- Use classes over generic element tag for optimum rendering performance.
- Avoid using several attribute selectors (e.g.,
[class^="..."]
) on commonly occuring components. Browser performance is known to be impacted by these. - Keep selectors short and strive to limit the number of elements in each selector to three.
- Scope classes to the closest parent only when necessary (e.g., when not using prefixed classes).
Additional reading:
Organization
- Organize sections of code by component.
- Develop a consistent commenting hierarchy.
- Use consistent white space to your advantage when separating sections of code for scanning larger documents.
- When using multiple CSS files, break them down by component instead of page. Pages can be rearranged and components moved.
Syntax
- Use hard tabs with four spaces.
- Remove all trailing white space.
- Always end you statements with a semicolon.
- Your opening braces go on the same line as the statement.
- Else opening should be on the same line as the if closing brace.
- If statements can be single line if they have a single return.
- Declare one variable per var statement, it makes it easier to re-order the lines. However, ignore Crockford when it comes to declaring variables deeper inside a function, just put the declarations wherever they make sense.
Naming Conventions
- Variables, properties and function names should use
lowerCamelCase
. They should also be descriptive. Single character variables and uncommon abbreviations should generally be avoided. - Class names should be capitalized using
UpperCamelCase
. - Constants should be declared as regular variables or static class properties, using all uppercase letters.
Conditionals
Use the === operator
Use the triple equality operator as it will work just as expected.
Use descriptive conditions
Any non-trivial conditions should be assigned to a descriptively named variable or function.
Functions
Write small functions
Keep your functions short. A good function fits on a slide that the people in the last row of a big room can comfortably read. So don't count on them having perfect vision and limit yourself to ~15 lines of code per function.
Return early from functions
To avoid deep nesting of if-statements, always return a function's value as early as possible.
Limit nested closures
There will always be times when you'll need to nest your closures, but limit the depth to ~3 deep otherwise your code can become unreadable and hard to maintain.
Method chaining
One method per line should be used if you want to chain methods.
You should also indent these methods so it's easier to tell they are part of the same chain.
Comments
Try to write comments that explain higher level mechanisms or clarify difficult segments of your code. Don't use comments to restate trivial things.
Miscellaneous
Object.freeze, Object.preventExtensions, Object.seal, with, eval
Crazy shit that you will probably never need. Stay away from it.
Requires At Top
Always put requires at top of file to clearly illustrate a file's dependencies. Besides giving an overview for others at a quick glance of dependencies and possible memory impact, it allows one to determine if they need a package.json file should they choose to use the file elsewhere.
Do not extend built-in prototypes
Do not extend the prototype of native JavaScript objects. Your future self will be forever grateful.
jQuery syntax
Always define a root node for every widget based off of the . This allows us to limit the size of the node tree when use functions like
.find()
which will improve performance. This will also help restrict any interactions, functions and listeners you define to the specific instance of the widget. Otherwise, other widgets or multiples of the same widget may trigger your code to run.
Avoid using class or id selectors
This helps keep a strict separation between structure and functionality. With this, an element can be completely restyled with an entire new set of classes and ids without any loss of functionality.
Cache your selectors
If you’re going to use a selector more than once, you should store it in a variable. Not only does it make the code easier to read, but it also improves performance since jQuery no longer has to traverse the DOM to find matching nodes.
Async/Await Guidelines
In order to effectively use async/await, you need to understand Promises, callbacks, and async/await. The following are some good resources for the basics.
Async/Await gives us the capability to utilize a synchronous programming style, but make asynchronous calls. There are numerous advantages to this style of programming. It avoids the pyramid of doom. It largely eliminates the need for 3rd party flow control libraries, such as async, flowly, co, bluebird. When done properly, it also eliminates the need for Node's flawed domain package.
Basic Tips:
- Tip 1: The return of an
async
function is always aPromise
, always. If the function text returns any non-Promise, it will be wrapped in aPromise
for you. - Tip 2: An
async
function returns synchronously, it'sPromise
returns asynchronously. This occurs if you are not usingawait
on theasync
function. - Tip 3: A thrown error in a async function, will be caught and wrapped as-if
Promise.reject(err)
was performed. - Tip 4: While inside an
async
function, if you ever bounce off the event loop, which means executing async code of any kind whether asetTimeout
or any other node-style error-first callback without utilizingawait
, you mustPromise
wrap it to avoid un-catchable errors. - Tip 5: util.promisify() is the preferred method for promisifying functions within Node since it's part of Node core.
- Tip 6: You can only utilize
await
within anasync
function. - Tip 7: If you utilize an
async
function in conjunction with the async library, then it no longer recieves a cb and your function can simply return a result, or return a Promise. This behavior is not available in flowly, it assumes you will still cb the response. - Tip 8: A
Promise
begins execution the moment it isnew
'd. It does not wait until anawait
orthen
to execute. Sometimes this can cause surprising results.
Editor preferences
Set your editor to the following settings to avoid common code inconsistencies and dirty diffs:
- Use hard-tabs set to four spaces.
- Trim trailing white space on save.
- Set encoding to UTF-8.
- Add new line at end of files.
Consider documenting and applying these preferences to your project's .editorconfig
file. You can use the one in this Code Guide. Learn more about EditorConfig. Get it for Sublime Text or Atom