directory

Naming Project

  • The project name
  • Directory name
  • JS file naming
  • CSS&SCSS file name
  • HTML file naming

HTML

  • grammar
  • HTML5 doctype
  • Language attributes
  • A character encoding
  • IE Compatible Mode
  • Introduce CSS and JavaScript
  • Practical over Perfect
  • Attribute order
  • Boolean attribute
  • Reduce the number of labels
  • JavaScript generated tags

CSS

  • The CSS syntax
  • The statement sequence
  • Don’t use @ import
  • Media Enquiry location
  • The prefix attribute
  • The declaration block of a single declaration
  • Attribute shorthand
  • Nested in Less and Sass
  • Code comments
  • The Class name
  • The selector
  • Code organization
  • Best guide to CSS by Harry Roberts

JavaScript

  • Indentation, semicolon, single line length
  • A blank line
  • Variable naming
  • Character constants
  • Null Usage Scenario
  • Undefined Usage Scenario
  • The Object literal
  • An Array literal
  • Single-line comments
  • Multiline comment
  • Documentation comments
  • Parentheses alignment
  • if else
  • switch
  • for
  • Variable declarations
  • Function declaration
  • miscellaneous
  • Editor configuration
  • GitHub’s larger and more comprehensive JavaScript code specification

Golden rule

open an issue

No matter how many people are working on the same project, make sure every line of code looks like it was written by the same person.

Project named

All project names are lowercase and separated by hyphens. For example: my project — the name

Directory name

Following the previous rule, use plural naming for directory names with plural structures, such as scripts, styles, images, data-models

JavaScript file naming

All JS file names that consist of multiple words are connected by hyphens, for example, account-model.js

CSS, SCSS file name

Use underlined links for multiple words, such as retina-sprites.scss

HTML file naming

If there are multiple words, use hyphens, for example, error-report-html

HTML

grammar

  • Use soft tabs with four Spaces – this is the only way to make sure your code looks consistent across environments.
  • Nested nodes should be indented (four Spaces).
  • On attributes, use double quotes, not single quotes.
  • Do not use slashes at the end of auto-closing tags – the HTML5 specification indicates that they are optional.
  • Do not ignore optional closing tags (for example,</li></body>).
<! DOCTYPE html> <html> <head> <title>Page title</title> </head> <body> <img src="images/company-logo.png" alt="Company"> <h1 class="hello-world">Hello, world! </h1> </body> </html>Copy the code

HTML5 doctype

Use this simple DOCType at the beginning of each HTML page to enable standard mode, rendering it as consistently as possible across browsers.

An article about HTML attributes, uppercase or lowercase

<! DOCTYPE html> <html> <head> </head> </html>Copy the code

Language attributes

According to the HTML5 specification:

It is strongly recommended to specify the lang attribute for the HTML root element to set the correct language for the document. This will help speech synthesis tools determine the pronunciation they should use, translation tools determine the rules they should follow when translating, and so on.

You can learn more about lang attributes from this specification.

Here is a list of language codes.

The above only gives the language code categories, for example, Chinese only gives ZH, but does not distinguish Hong Kong, Taiwan, mainland and so on. A detailed list of language codes provided by Microsoft subdivides zh-CN, zh-HK, zh-TW, Head to Microsoft for a detail list of language codes.

Should the declaration in the header of the webpage be lang=”zh” or lang=”zh-cn”?

zh-CN

<html lang="en-us"> <! -... --> </html>Copy the code

IE compatibility mode

IE supports specific
tags to determine which version of IE should be used to draw the current page. Unless there is a strong special need, it is best to set edge mode to inform IE to adopt the latest mode it supports.

Read this article on Stack Overflow for more useful information.

That sums it up nicely

<meta http-equiv="X-UA-Compatible" content="IE=Edge">Copy the code

A character encoding

By declaring an explicit character encoding, browsers can easily and quickly determine how to render web content. You should also avoid using Entities such as < Entities and use their entity_code <.

<head>
    <meta charset="UTF-8">
</head>Copy the code

Introduce CSS and JavaScript

According to the HTML5 specification, there is usually no need to specify type when introducing CSS and JavaScript, since text/ CSS and text/ JavaScript are their default values, respectively.

HTML5 specification link

  • Use the link
  • Use the style
  • Use the script
<! -- External CSS --> <link rel="stylesheet" href="code-guide.css"> <! -- In-document CSS --> <style> /* ... */ </style> <! -- JavaScript --> <script src="code-guide.js"></script>Copy the code

Practical over Perfect

Try to follow HTML standards and semantics, but not at the expense of usability. Solve problems with as little complexity and as few tags as possible at all times.

Attribute order

HTML attributes should appear in a specific order to ensure readability.

  • class
  • id
  • name
  • data-*
  • src.for.type.href.value , max-length.max.min.pattern
  • placeholder.title.alt
  • aria-*.role
  • required.readonly.disabled

Classes are designed for highly reusable components, and theoretically they should be in the first place. Ids are more specific and should be used as little as possible (for example, in-page bookmarks), so they come in second place.

<a id="..." class="..." data-modal="toggle" href="#"> Example link </a> <input class="form-control" type="text"> <img src="..." alt="..." >Copy the code

Boolean attribute

Boolean attributes are attributes that do not require a value to be declared. XHTML requires each attribute to declare a value, but HTML5 does not.

To learn more, see WhatWG Section on Boolean Attributes:

The presence of a Boolean attribute in an element indicates that the value is true; its absence indicates that the value is false.

If you must add unnecessary values to attributes, follow the WhatWG guidelines:

If the attribute exists, its value must be an empty string or […]. The canonical name of the property, without whitespace characters at the beginning or end.

In short, do not add values to Boolean attributes.

<input type="text" disabled>

<input type="checkbox" value="1" checked>

<select>
    <option value="1" selected>1</option>
</select>Copy the code

Reduce the number of labels

When writing HTML code, you need to avoid redundant parent nodes. Many times, you need to iterate and refactor to make HTML less. See the following example:

<! -- Not so great --> <span class="avatar"> <img src="..." > </span> <! -- Better --> <img class="avatar" src="..." >Copy the code

JavaScript generated tags

Generating tags in JavaScript files makes content harder to find, harder to edit, and worse performance. This should be avoided as much as possible.

CSS

grammar

  • Use soft tabs with four Spaces – this is the only way to make sure your code looks consistent across environments.
  • When using composite selectors, keep each individual selector on one row.
  • For legibility of code, add a space before the opening parenthesis of each declaration.
  • The closing bracket of the declaration block should start on a separate line.
  • Each statement:A space should be inserted after it.
  • Each statement should take only one line to ensure accurate error reporting.
  • All declarations should end with a semicolon. The semicolon after the last declaration is optional, but without it, your code is more prone to errors.
  • All comma-separated values should be followed by a space. Such as box – shadow
  • Do not use color valuesrgb() rgba() hsl() hsla()andrect() In theAdd whitespace and do not precede values with unnecessary zeros (for example, use.5 instead of 0.5). This helps differentiate multiple color values (comma, no space) from multiple property values (comma with space).
  • All hexadecimal values should be lowercase, for example#fff. Because lowercase letters have a greater variety of shapes, they can be more easily distinguished when browsing documents.
  • Use as short a hexadecimal value as possible, e.g#fffalternative#ffffff.
  • Add quotes to attribute values in the selector, for exampleinput[type="text"].They are only dispensable in certain circumstances, so use quotation marks for consistency.
  • Do not specify units for 0, such as usemargin: 0;Rather thanmargin: 0px;.

CSS Syntax section

/* Bad CSS */ .selector, .selector-secondary, .selector[type=text] { padding: 15px; margin: 0px 0px 15px; Background: rgba(0, 0, 0, 0.5); box-shadow: 0 1px 2px #CCC, inset 0 1px 0 #FFFFFF } /* Good CSS */ .selector, .selector-secondary, .selector[type="text"] { padding: 15px; margin-bottom: 15px; Background - color: rgba (0, 0, 5); box-shadow: 0 1px 2px #ccc, inset 0 1px 0 #fff; }Copy the code

The statement sequence

Related attribute declarations should be grouped in the following order:

  1. Positioning
  2. Box model
  3. Typographic layout
  4. The Visual appearance

Positioning comes first, as it can take an element out of the normal text flow and overwrite the style associated with the box model. The box model follows, as it determines the size and location of a component.

The other attributes work only inside the component or have no effect on the results of the first two cases, so they come later.

Recess

.declaration-order { /* Positioning */ position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: 100; /* Box-model */ display: block; float: right; width: 100px; height: 100px; /* Typography */ font: normal 13px "Helvetica Neue", sans-serif; The line - height: 1.5; color: #333; text-align: center; /* Visual */ background-color: #f5f5f5; border: 1px solid #e5e5e5; border-radius: 3px; /* Misc */ opacity: 1; }Copy the code
// For easy reference, I posted a copy of the order of the Recess and introduced the time 2014-05-05 // CSS property order var order = ['position', 'top', 'right', 'bottom', 'left' , 'z-index' , 'display' , 'float' , 'width' , 'height' , 'max-width' , 'max-height' , 'min-width' , 'min-height' , 'padding' , 'padding-top' , 'padding-right' , 'padding-bottom' , 'padding-left' , 'margin' , 'margin-top' , 'margin-right' , 'margin-bottom' , 'margin-left' , 'margin-collapse' , 'margin-top-collapse' , 'margin-right-collapse' , 'margin-bottom-collapse' , 'margin-left-collapse' , 'overflow' , 'overflow-x' , 'overflow-y' , 'clip' , 'clear' , 'font' , 'font-family' , 'font-size' , 'font-smoothing' , 'osx-font-smoothing' , 'font-style' , 'font-weight' , 'hyphens' , 'src' , 'line-height' , 'letter-spacing' , 'word-spacing' , 'color' , 'text-align' , 'text-decoration' , 'text-indent' , 'text-overflow' , 'text-rendering' , 'text-size-adjust' , 'text-shadow' , 'text-transform' , 'word-break' , 'word-wrap' , 'white-space' , 'vertical-align' , 'list-style' , 'list-style-type' , 'list-style-position' , 'list-style-image' , 'pointer-events' , 'cursor' , 'background' , 'background-attachment' , 'background-color' , 'background-image' , 'background-position' , 'background-repeat' , 'background-size' , 'border' , 'border-collapse' , 'border-top' , 'border-right' , 'border-bottom' , 'border-left' , 'border-color' , 'border-image' , 'border-top-color' , 'border-right-color' , 'border-bottom-color' , 'border-left-color' , 'border-spacing' , 'border-style' , 'border-top-style' , 'border-right-style' , 'border-bottom-style' , 'border-left-style' , 'border-width' , 'border-top-width' , 'border-right-width' , 'border-bottom-width' , 'border-left-width' , 'border-radius' , 'border-top-right-radius' , 'border-bottom-right-radius' , 'border-bottom-left-radius' , 'border-top-left-radius' , 'border-radius-topright' , 'border-radius-bottomright' , 'border-radius-bottomleft' , 'border-radius-topleft' , 'content' , 'quotes' , 'outline' , 'outline-offset' , 'opacity' , 'filter' , 'visibility' , 'size' , 'zoom' , 'transform' , 'box-align' , 'box-flex' , 'box-orient' , 'box-pack' , 'box-shadow' , 'box-sizing' , 'table-layout' , 'animation' , 'animation-delay' , 'animation-duration' , 'animation-iteration-count' , 'animation-name' , 'animation-play-state' , 'animation-timing-function' , 'animation-fill-mode' , 'transition' , 'transition-delay' , 'transition-duration' , 'transition-property' , 'transition-timing-function' , 'background-clip' , 'backface-visibility' , 'resize' , 'appearance' , 'user-select' , 'interpolation-mode' , 'direction' , 'marks' , 'page' , 'set-link-source' , 'unicode-bidi' , 'speak' ]Copy the code

Don’t use@import

The @import directive is much slower than the tag, not only adding extra requests, but also causing unexpected problems. Alternatives are as follows:

  • The use of multiple<link>The element
  • Compile multiple CSS files into a single file with a CSS preprocessor like Sass or Less
  • CSS file merging has been provided through Rails, Jekyll, or other systems

Steve Souders article

<! -- Use link elements --> <link rel="stylesheet" href="core.css"> <! -- Avoid @imports --> <style> @import url("more.css"); </style>Copy the code

Media Enquiry location

Try to locate media queries close to their relevant rules. Don’t put them together in a separate style file or throw them at the bottom of the document. It just makes it easier for everyone to forget about them later. Here is a typical case.

.element { ... }
.element-avatar { ... }
.element-selected { ... }

@media (min-width: 480px) {
    .element { ...}
    .element-avatar { ... }
    .element-selected { ... }
}Copy the code

The prefix attribute

When using the vendor prefix attribute, align values vertically by indentation for multi-line editing.

Text → Edit Each Line in Selection
Selection → Add Previous Line
Selection → Add Next Line

/* Prefixed properties */. Selector {-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.15); Box-shadow: 0 1px 2px rgba(0,0,0,.15); }Copy the code

The declaration block of a single declaration

In cases where a declaration block contains only one declaration, consider removing line breaks for legibility and quick editing. All declaration blocks containing multiple declarations should be divided into multiple lines.

The key element to doing this is error detection – for example, a CSS validator that says you have a syntax error on line 183, if it’s a single declared line, that’s it. In the case of multiple declarations, you have to think about what went wrong.

/* Single declarations on one line */ .span1 { width: 60px; } .span2 { width: 140px; } .span3 { width: 220px; } /* Multiple declarations, one per line */ .sprite { display: inline-block; width: 16px; height: 15px; background-image: url(.. /img/sprite.png); } .icon { background-position: 0 0; } .icon-home { background-position: 0 -20px; } .icon-account { background-position: 0 -40px; }Copy the code

Attribute shorthand

Do restrict the use of property shorthand, which requires you to explicitly set all values. Common attribute shorthand abuses include:

  • padding
  • margin
  • font
  • background
  • border
  • border-radius

In most cases, we do not need to set all the values contained in the property shorthand. For example, the HTML header only sets the margin above and below, so only set those two values if necessary. Overuse of attribute abbreviations often leads to more cluttering code, with unnecessary rewrites and unintended side effects.

shorthand properties

/* Bad example */
.element {
    margin: 0 0 10px;
    background: red;
    background: url("image.jpg");
    border-radius: 3px 3px 0 0;
}

/* Good example */
.element {
    margin-bottom: 10px;
    background-color: red;
    background-image: url("image.jpg");
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
}Copy the code

Nested in Less and Sass

Avoid unnecessary nesting. Just because you can nest doesn’t mean you should. Nesting is only considered if you need to style the parent element and if there are multiple child elements.

Nesting. Table > thead > tr > th {... }. Table > thead > tr > TD {... } // With nesting. Table > thead > tr {> th {... } > td {... }}Copy the code

The Class name

  • Keep the Class name all lowercase, and you can use a dash (no underscores and camelCase names). The dash should be used as a natural discontinuity of the related class. (e.g.,.btn.btn-danger).
  • Avoid overusing abbreviations..btnIt can be described very wellbutton, but.sDoes not represent any element.
  • Class names should be as short and unambiguous as possible.
  • Use meaningful names; Use structured or target-specific names rather than abstract names.
  • The name is prefixed with the nearest parent node or the parent class.
  • use.js-*Classes represent behavior (as opposed to style), but do not include these classes in CSS.
/* Bad example */
.t { ... }
.red { ... }
.header { ... }

/* Good example */
.tweet { ... }
.important { ... }
.tweet-header { ... }Copy the code

The selector

  • Use classes instead of generic element tags to optimize rendering performance.
  • Avoid using property selectors in common components (for example,[class^="..."]). Browser performance can be affected by these conditions.
  • Reduce the length of the selector and try to limit the number of entries per combinatorial selector to three.
  • Use descendant selectors only when necessary (for example, when prefixed classes are not used).

Read more:

  • Scope CSS classes with prefixes
  • Stop the cascade
/* Bad example */
span { ... }
.page-container #stream .stream-item .tweet .tweet-header .username { ... }
.avatar { ... }

/* Good example */
.avatar { ... }
.tweet-header .username { ... }
.tweet .avatar { ... }Copy the code

Code organization

  • Organize code by component.
  • Develop a consistent annotation hierarchy.
  • Use consistent white space to split code blocks to have an advantage when viewing large documents.
  • When working with multiple CSS files, distinguish them by components rather than pages. The page is rearranged and the components are moved.
/* * Component section heading */ .element { ... } /* * Component section heading * * Sometimes you need to include optional context for the entire component. Do that up  here if it's important enough. */ .element { ... } /* Contextual sub-component or modifer */ .element-heading { ... }Copy the code

Editor configuration

Configure your editor according to the following Settings to avoid common code inconsistencies and ugly Diffs.

  • Use soft-tabs with four Spaces.
  • Remove trailing whitespace characters when saving.
  • Remove trailing whitespace characters when saving. Why do you do that?
  • Set the file encoding to UTF-8.
  • Add a blank line at the end of the file.
  • Add a blank line at the end of the file. Why do you do that?

.editorconfig
The Bootstrap.editorconfigfile
About EditorConfig

JavaScript

Indentation, semicolon, single line length

  • Use all four Spaces
  • Continuation -indentation also applies with 4 Spaces, aligned with the last line
  • Statement must end with a semicolon (;)
  • The single-line length should theoretically be no more than 80 columns, although the single-line length can be ignored if the editor turns on Soft Wrap
  • If a line break is required, the operator must be followed by a line break, followed by an indent of 4 Spaces
  • Notice that if you have multiple line feeds you don’t have to indent any more, like the second paragraph on the right is the best format.
if (typeof qqfind === "undefined" || typeof qqfind.cdnrejected === "undefined" || qqfind.cdnrejected ! == true) { url = "http://pub.idqqimg.com/qqfind/js/location4.js"; } else { url = "http://find.qq.com/js/location4.js"; }Copy the code

A blank line

  • Add between methods
  • Add before a single or multiple line comment
  • Add blank lines between logical blocks to increase readability

Variable naming

  • Standard variables are humped
  • Use all caps for the ID
  • Always use all uppercase urls, such as reportURL
  • When it comes to Android, capitalize the first letter
  • IOS, all lowercase first, uppercase last two letters
  • Constants are capitalized and underlined
  • Constructor, uppercase the first letter
var thisIsMyName;

var goodID;

var AndroidVersion;

var iOSVersion;

var MAX_COUNT = 10;

function Person(name) {
    this.name = name
}Copy the code

Character constants

  • Generally, ” single quotation marks are used

Null usage scenarios

  • To initialize a variable that may later be assigned an object value
  • To compare against an initialized variable that may or may not have an object value
  • To pass into a function where an object is expected
  • To return from a function where an object is expected

Not suitable for null usage scenarios

  • Do not use null to test whether an argument was supplied
  • Do not test an uninitialized variable for the value null

Undefined Usage Scenario

  • Never use undefined directly for variable judgments
  • Use the string “undefined” to determine variables
// Bad
var person;
console.log(person === undefined);    //true

// Good
console.log(typeof person);    // "undefined"Copy the code

Object Literals

// Bad var team = new Team(); team.title = "AlloyTeam"; team.count = 25; Var team = {title: "AlloyTeam", count: 25};Copy the code

Array Literals

// Bad
var colors = new Array("red", "green", "blue");
var numbers = new Array(1, 2, 3, 4);


// Good
var colors = [ "red", "green", "blue" ];
var numbers = [ 1, 2, 3, 4 ];Copy the code

Parentheses alignment

  • In the standard example, there are Spaces before and after parentheses. The curly braces do not start with a new line, but end with a new line
  • Curly braces are mandatory, even if the content is only one line, never allow the second case on the right
  • Involves if for while doing… while try… catch… You must use curly braces everywhere in finally
// Good
if (condition) {
    doSomething();
}

if (condition)
    doSomething();
    doSomethingElse();Copy the code

Leave Spaces before and after if else else

if (condition) {
    doSomething();
} else {
    doSomethingElse();
}Copy the code

switch

  • Use the format on the right, with Spaces between switch and parentheses, indent case, and leave a blank line between break and the next case
  • Curly braces are required, even if the content is only one line.
  • For the second case on the right, the switch’s falling through must be specified, and the case of no default must also be specified
switch (condition) { case "first": // code break; case "third": // code break; Default: // code} switch (condition) {// obvious fall through case "second": // code break; Case "third": // code /* falls through */ // code } switch(condition) { case "first": // code break; case "second": // code break; // no default }Copy the code

for

  • In a normal for loop, a semicolon is followed by a space, and no Spaces are left on either side of the operators in the criteria. If there are multiple preconditions, a space is left after the comma
  • For-in must have a hasOwnProperty judgment, otherwise either JSLint or JSHint will have a WARN
var values = [ 1, 2, 3, 4, 5, 6, 7 ], i, len; for (i=0, len=values.length; i<len; i++) { process(values[i]); } var prop; For (prop in Object) {// Note that hasOwnProperty must be declared, otherwise either JSLint or JSHint will have a WARN! if (object.hasOwnProperty(prop)) { console.log("Property name is " + prop); console.log("Property value is " + object[prop]); }}Copy the code

Variable declarations

  • All function variable declarations are placed in the header of the function, using only one var, one variable line, and a comment at the end of the line, comment, comment, pro
Function doSomethingWithItems(items) {result = value + 2; function doSomethingWithItems(items) {function doSomethingWithItems(items) {result = value + 3;  For (I =0, len=items. Length; i < len; i++) { doSomething(items[i]); }}Copy the code

Function declaration

  • Never use the JavaScript engine hoist. JSLint and JSHint warn when the JavaScript engine is hoist
  • Function declaration is different from function expression. Function expression () must have Spaces before and after it. Function declaration does not need Spaces when it has function names. Spaces are required when there is no function name.
  • Function calls do not require Spaces before or after parentheses
  • To write the function immediately, the outermost layer of parentheses must be wrapped
  • “Use strict” is never allowed globally and must be on the first line of a function. You can include large sections of code with self-executing functions. If “use strict” is used outside of a function, both JSLint and JSHint will report an error
function doSomething(item) {
    // do something
}

var doSomething = function (item) {
    // do something
}


// Good
doSomething(item);

// Bad: Looks like a block statement
doSomething (item);


// Good
var value = (function() {

    // function body
    return {
        message: "Hi"
    }
}());


// Good
(function() {
    "use strict";

    function doSomething() {
        // code
    }

    function doSomethingElse() {
        // code
    }

})();Copy the code

miscellaneous

  • Completely avoid ==! = is used with strict comparison conditions ===! = =
  • Eval is not a special business, disabled!!
  • With non-special business, disabled!!

Editor configuration

Configure your editor according to the following Settings to avoid common code inconsistencies and ugly Diffs.

  • Use two Spaces instead of tabs (soft-tab: Spaces for tabs).
  • Remove trailing whitespace characters when saving. Why do you do that?
  • Set the file encoding to UTF-8.
  • Add a blank line at the end of the file. Why do you do that?

Refer to the documentation to apply these Settings to your project’s.EditorConfig file. For example, the.editorConfig file in Bootstrap. Learn more about EditorConfig.