Front-end code style

file name

Are in lower case, underlined separated, if a plurality of structures, the use of complex nomenclature

  • Directory name: scripts, styles, images,data-models

  • file name: example.js retina-sprites.css

Javascript

Note

When to Use

  • Difficult to understand snippet

  • There may be an error code snippet

  • Special browser HACK Code

  • I would like Tucao of logic products, cooperation colleague

  • Strongly related to the business logic code

// 单行注释斜杠后面要留有一个空格

/*
 * 多行注释最少三行,注释内容与星标前保留一个空格
 */
 
 var hello = '';        // 描述变量可以这样写在变量右边
 
/*
 * 描述方法(函数)必须使用多行描述
 * 如有必要可以加上参数和返回值说明,参考 http://usejsdoc.org/
 * @param {Object} balabalabala
 * @return {Object} balabalabala
 */
 function foo() {
     // 描述下面代码时做什么的,方法第一行不需要留空格
     doSomething();
     
     // 描述下面代码时做什么的,上方需要留一个空行
     afterDoSomething();
     
     if (flag) {
         // 描述下面代码时做什么的,代码块的第一行也不需要留空格
         drive();
     }
 }

grammar

  • Use four spaces soft tabs - this is the only way to ensure consistent code is displayed in a variety of environments.

  • Under normal circumstances there should be a space where keywords

  • String use single quotes instead of double quotes: `var str = 'hello world';`

  • Single line length, in theory, not more than 80, but if the editor is turned soft wrap, then we can not consider the length of a single line

  • Connected to a, if desired wrap, the presence of the operator, the operator must change the row, then a row change indented four spaces

  • Note here that if wrap is repeatedly then there is no need to continue indented, for example, this is the best format below.

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";
}

Creates an Object object

// Bad
var team = new Team();
team.title = "AlloyTeam";
team.count = 25;

// Good  
var team = {
    title: "AlloyTeam",        // 冒号后需要跟一个空格
    count: 25
};

Creating Array Objects

// 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 ];

Constructor

/**
 * 创建一个构造函数
 */
function Modal(options) {    // 函数名使用大写字母开头,驼峰式命名
    this.width = options.width;    // 属性在构造函数体中定义
    this.height = options.height;
}

Modal.prototype.show = function() {    // 方法定义在原型链上
    // show
}

Modal.prototype.hide = function() {
    // hide
}

// 实例化对象
var modal = new Modal({
        width: 200,
        height: 300
    });

if grammar

// if else 前后留有空格,
if (flag) {

} else {

}

for grammar

// 普通for
var values = [ 1, 2, 3, 4, 5, 6, 7 ],
    i, len;
for (i=0, len=values.length; i<len; i++) {
    process(values[i]);
}

// for in, (一般情况下不要用for in)
var prop;
for (prop in object) {
    // 注意这里一定要有 hasOwnProperty 的判断,不要把原型链上的属性枚举出来
    if (object.hasOwnProperty(prop)) {
        console.log("Property name is " + prop);
        console.log("Property value is " + object[prop]);
    }
}

switch grammar

// switch和括号之间有空格, case需要缩进, break之后跟下一个case中间留一个空行
switch (condition) {
    case "first":
        // code
        break;

    case "third":
        // code
        break;

    default:
    // code
}

// 没有default的情况需要注释特别说明
switch(condition) {
    case "first":
        // code
        break;

    case "second":
        // code
        break;

    // no default
}

statement

Variable declaration

var _body = $(document.body); // 全局变量使用下划线 _ 开头
function foo() {
    var result,    // 一个代码块里的变量声明只用一个var
         length,    // 一个变量一行,行末跟注释
         mainWrap;// 驼峰式命名法
         
}

Constant declaration

Use all capital letters + naming manner underlined

var IMAGE_DOMAIN = 'WWW.XXX.COM';     

Function declarations

  • Unified command function declaration is declared using the function

// good
function foo() {        // 小括号前不需要空格,小括号与大括号间需要一个空格
    doSomething(); // 函数调用括号前后不需要空格
    return "hello world";
}

// bad
var foo = function() {
    return "hello world";
}

// bad
var foo = new Function(
    'return "hello world"'
);
  • Now wording execution of the function, the outermost layer of the package must bracket

// Good
(function() {
    "use strict";    // 使用严格模式

    function doSomething() {
        // code
    }

    function doSomethingElse() {
        // code
    }

})();

Blank line

Description: Note the following code represents a blank line in the actual code

function foo1() {
    
}
// 方法之间加空行
function foo2() {
    
}
// 逻辑块与方法之间加空行增加可读性
for (var i=0; i<10; i++) {
    
} 
// 逻辑块之间加空行增加可读性
if (flag) {
    
} else {
    
}
// 文件结尾留一个空行

Miscellaneous

  • Only string type allows the use of == !=such if(x == 'a')other cases shall be strictly comparable with the conditions ===! ==

  • eval non-special service, disabled! ! !

  • with non-special service, disabled! ! !

CSS

grammar

  • When using a combination of selectors, each holding a separate selector occupies one row.

  • For readability of the code, add a space before the opening parenthesis for each statement.

  • Right parenthesis declaration block should be a separate line.

  • Each statement is: When should insert a space.

  • Each statement should occupy only one line to ensure more accurate error reporting.

  • All statements must end with a semicolon. Although the semicolon after the last statement is optional, but if he does not, your code will be more prone to error.

  • Comma-separated values, should add a space after the comma. For example, box-shadow

  • Do not color values ​​rgb () rgba () hsl () hsla () and rect () adds space

  • Do with unnecessary preceding value 0 (for example, use of alternative .5 0.5).

  • All hexadecimal values ​​should be lowercase letters, for example #fff. Because lowercase letters have a greater variety of shape, when browsing the document, they can more easily be distinguished.

  • Add quotes attribute value selectors, such input [type = "text"]. In some cases they are only an option, so use quotation marks can increase consistency.

  • Do not specify 0 units, such as the use margin: 0; instead margin: 0px ;.

/* Bad CSS */
.selector, .selector-secondary, .selector[type=text] {
    padding: 15px;
    margin: 0px 0px 15px;
    background-color: rgba(0, 0, 0, 0.5);
    box-shadow: 0 1px 2px #C0C0C0, inset 0 1px 0 #F8F8F8
}

/* Good CSS */
.selector,
.selector-secondary,
.selector[type="text"] {
    padding: 15px;
    margin-bottom: 15px;
    background-color: rgba(0,0,0,.5);
    box-shadow: 0 1px 2px #c0c0c0, inset 0 1px 0 #f8f8f8;
}

Declaration order

Attribute declaration should be related in the following order of the packet processing:

  1. Positioning

  2. Box model The box model

  3. Typographic layout

  4. Visual Appearance

Positioning at first, because he can make an element out of the normal text flow, and box model covering the relevant style. Box model followed, because he determines the size and location of a component.

Other attributes only work within the component or does not affect the results of the previous two cases, so they are at the back.

For a complete attributes and their order, please refer to 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;
    line-height: 1.5;
    color: #333;
    text-align: center;

    /* Visual */
    background-color: #f5f5f5;
    border: 1px solid #e5e5e5;
    border-radius: 3px;

    /* Misc */
    opacity: 1;
}

Class name

  • Keeping Class name all lowercase, you can use the dash (Do not use the underscore and camelCase name). Dash should be as natural breaks related classes. (E.g., .btn, and .btn-danger).

  • Avoid excessive use of abbreviations. .btnIt can be well described by the Button , but .snot on behalf of any element.

  • Use .js-*classes to represent the behavior (with respect to the style), but do not include these classes in the CSS.

/* Bad example */
.t { ... }
.red { ... }
.header { ... }

/* Good example */
.tweet { ... }
.important { ... }
.tweet-header { ... }

Selector

  • Use classes instead of a generic label elements to optimize rendering performance.

  • Avoid using attribute selectors (e.g., [class ^ = "..."]) appears frequently in assembly. Browser performance will be affected by these conditions.

  • Reducing the length of the selector, selecting each combination of selector entries should ideally controlled within 3.

  • Only descendant selector if necessary (e.g., without the use of the classes with the prefix).

/* Bad example */
span { ... }
.page-container #stream .stream-item .tweet .tweet-header .username { ... }
.avatar { ... }

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

Do not use @import

And <link>compared to the label @importinstructions to be much slower, not only adds additional number of requests, but also lead to unexpected problems. There are several alternatives:

  • The use of multiple <link>elements

  • Less Sass or the like by the preprocessor CSS CSS files compiled as a plurality of file

HTML

grammar

  • With two spaces instead of tabs (tab) - This is the only way to guarantee access to the same method demonstrated in all environments.

  • On the property, use double quotes, do not use single quotation marks.

  • Do not use the label automatically closed at the end of slash - HTML5 specification states that they are optional.

  • Do not overlook the optional closing tag (e.g., </ li> and </ body>).

  • Nested nodes should be indented (four spaces).

Character Encoding

By explicitly declare the character encoding, you can ensure that your browser quickly and easily judge rendering the page content. The benefit of this is to avoid the use of character entity tag (character entity) in HTML, so all consistent with the document encoding (generally use UTF-8 encoding).

The introduction of CSS and JavaScript

According to the HTML5 specification, usually you do not need to specify the type when introducing CSS and JavaScript, as text / css and text / javascript are their default values.

Attribute Order

HTML attributes as they appear to be a specific order to ensure legibility.

  • 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 with high-reusable components, in theory, they should be in the first place. Ids more specific and should minimize the use (eg, within a page bookmark), so they are in second place.

Do not use JavaScript to generate labels

Generated content label to make it more difficult to find, harder to edit, worse performance in the JavaScript file. We should try to avoid this situation.

Sample Code


<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <!-- External CSS -->
    <link rel="stylesheet" href="code-guide.css">
    <!-- In-document CSS -->
    <style>
      /* ... */
    </style>
  </head>
  <body>
    <a id="..." class="..." data-modal="toggle" href="#">
      Example link
    </a>
    <input class="form-control" type="text">
    <img src="..." alt="...">
    
    <!-- JavaScript -->
    <script src="code-guide.js"></script>
  </body>
</html>


Guess you like

Origin www.cnblogs.com/homehtml/p/12575941.html