Frontend Guidelines
HTML
Semantics(語義化)
為了更精確地描述我們的網(wǎng)頁內(nèi)容,HTML5提供了許多語義化標(biāo)簽,你應(yīng)該確保從豐富的詞匯中受益:
<!-- bad -->
<div id="main">
<div class="article">
<div class="header">
<h1>Blog post</h1>
<p>Published: <span>21st Feb, 2015</span></p>
</div>
<p>…</p>
</div>
</div>
<!-- good -->
<main>
<article>
<header>
<h1>Blog post</h1>
<p>Published: <time datetime="2015-02-21">21st Feb, 2015</time></p>
</header>
<p>…</p>
</article>
</main>
確保理解你使用的元素的語義,錯(cuò)誤地使用一個(gè)語義比不用更糟糕。
<!-- bad -->
<h1>
<figure>
<img alt=Company src=logo.png>
</figure>
</h1>
<!-- good -->
<h1>
<img alt=Company src=logo.png>
</h1>
Brevity(簡介)
讓你的代碼簡潔。忘記你的舊的XHTML的習(xí)慣。
<!-- bad -->
<!doctype html>
<html lang=en>
<head>
<meta http-equiv=Content-Type content="text/html; charset=utf-8" />
<title>Contact</title>
<link rel=stylesheet href=style.css type=text/css />
</head>
<body>
<h1>Contact me</h1>
<label>
Email address:
<input type=email placeholder=you@email.com required=required />
</label>
<script src=main.js type=text/javascript></script>
</body>
</html>
<!-- good -->
<!doctype html>
<html lang=en>
<meta charset=utf-8>
<title>Contact</title>
<link rel=stylesheet href=style.css>
<h1>Contact me</h1>
<label>
Email address:
<input type=email placeholder=you@email.com required>
</label>
<script src=main.js></script>
</html>
Accessibility(可訪問性)
可訪問性不是個(gè)事后想法,你不必是一個(gè)WCAG專家來改善你的
網(wǎng)站,你可以立即開始通過固定的小東西,達(dá)到一個(gè)巨大的效果,如:
- 學(xué)會(huì)合理的使用
alt屬性 - 不是完全依賴顏色來進(jìn)行信息交流
*顯式標(biāo)記窗體控件
<!-- bad -->
<h1><img alt="Logo" src="logo.png"></h1>
<!-- good -->
<h1><img alt="My Company, Inc." src="logo.png"></h1>
Language(語言)
定義語言和字符編碼是可選的,建議總是聲明它們?yōu)槲臋n級別的,即使他們在你的HTTP標(biāo)頭中指定。在任何其他支持UTF-8字符編碼
<!-- bad -->
<!doctype html>
<title>Hello, world.</title>
<!-- good -->
<!doctype html>
<html lang=en>
<meta charset=utf-8>
<title>Hello, world.</title>
</html>
Performance(性能)
除非有必要的理由,否則不要讓你的script文件阻止渲染你的頁面。如果你的樣式表是沉重的,隔離最初的風(fēng)格絕對必需,并將二次聲明的延遲加載在一個(gè)單獨(dú)的樣式表中。
兩個(gè)HTTP請求比明顯變慢,但速度的感知是最重要的因素。
<!-- bad -->
<!doctype html>
<meta charset=utf-8>
<script src=analytics.js></script>
<title>Hello, world.</title>
<p>...</p>
<!-- good -->
<!doctype html>
<meta charset=utf-8>
<title>Hello, world.</title>
<p>...</p>
<script src=analytics.js></script>
CSS
Semicolons(分號)
當(dāng)分號是CSS技術(shù)上的分離器時(shí),應(yīng)該總是用它來結(jié)束語句。
/* bad */
div {
color: red
}
/* good */
div {
color: red;
}
Box model(盒子模型)
盒子模型應(yīng)該為整個(gè)文檔是一樣的。一個(gè)全局的 “* { box-sizing:border-box;}” 是可以的,但,如果你能避免的話,請不要在特定元素里面改變它的默認(rèn)盒模型。
/* bad */
div {
width: 100%;
padding: 10px;
box-sizing: border-box;
}
/* good */
div {
padding: 10px;
}
Flow
能避免的話,不要改變一個(gè)元素的默認(rèn)行為。盡可能保持它的自然文本流。例如,移除圖片下面的空白間隙不應(yīng)該改變圖片的默認(rèn)顯示。
/* bad */
img {
display: block;
}
/* good */
img {
vertical-align: middle;
}
同樣,盡量不要使元素脫離文本流。
/* bad */
div {
width: 100px;
position: absolute;
right: 0;
}
/* good */
div {
width: 100px;
margin-left: auto;
}
Positioning(定位)
There are many ways to position elements in CSS but try to restrict yourself to the properties/values below. By order of preference:
在CSS有很多方法來定位元素,但是盡可能限制自己的屬性/值在下面。按優(yōu)先順序:
display: block;
display: flex;
position: relative;
position: sticky;
position: absolute;
position: fixed;
Selectors(選擇器)
減少緊密耦合DOM的選擇器。當(dāng)您的選擇器超過了3個(gè)結(jié)構(gòu)的偽類、后代或兄弟選擇器,考慮添加一個(gè)類到要匹配的元素。
/* bad */
div:first-of-type :last-child > p ~ *
/* good */
div:first-of-type .info
Avoid overloading your selectors when you don't need to.
/* bad */
img[src$=svg], ul > li:first-child {
opacity: 0;
}
/* good */
[src$=svg], ul > :first-child {
opacity: 0;
}
Specificity(專一性)
不要使屬性值和選擇器難以覆蓋,減少使用“id”和避免使用“!important”。
/* bad */
.bar {
color: green !important;
}
.foo {
color: red;
}
/* good */
.foo.bar {
color: green;
}
.foo {
color: red;
}
Overriding
覆蓋樣式使選擇器和調(diào)試變得困難,盡量避免
/* bad */
li {
visibility: hidden;
}
li:first-child {
visibility: visible;
}
/* good */
li + li {
visibility: hidden;
}
Inheritance
不要重復(fù)可以繼承的樣式。
/* bad */
div h1, div p {
text-shadow: 0 1px 0 #fff;
}
/* good */
div {
text-shadow: 0 1px 0 #fff;
}
Brevity(簡潔)
保持你代碼的簡潔性。使用簡寫屬性,并避免使用多個(gè)屬性在非必要時(shí)。
/* bad */
div {
transition: all 1s;
top: 50%;
margin-top: -10px;
padding-top: 5px;
padding-right: 10px;
padding-bottom: 20px;
padding-left: 10px;
}
/* good */
div {
transition: 1s;
top: calc(50% - 10px);
padding: 5px 10px 20px;
}
Language(語言)
喜歡英語勝過數(shù)學(xué)。
/* bad */
:nth-child(2n + 1) {
transform: rotate(360deg);
}
/* good */
:nth-child(odd) {
transform: rotate(1turn);
}
Vendor prefixes(前綴)
Kill obsolete vendor prefixes aggressively. If you need to use them, insert them before the
standard property.
不要使用過時(shí)的前綴。如果你需要使用它們,把它們插入標(biāo)準(zhǔn)屬性之前。
/* bad */
div {
transform: scale(2);
-webkit-transform: scale(2);
-moz-transform: scale(2);
-ms-transform: scale(2);
transition: 1s;
-webkit-transition: 1s;
-moz-transition: 1s;
-ms-transition: 1s;
}
/* good */
div {
-webkit-transform: scale(2);
transform: scale(2);
transition: 1s;
}
Animations(動(dòng)畫)
transitions 好于 animations. 避免使opacity and transform以外的屬性產(chǎn)生動(dòng)畫效果.
/* bad */
div:hover {
animation: move 1s forwards;
}
@keyframes move {
100% {
margin-left: 100px;
}
}
/* good */
div:hover {
transition: 1s;
transform: translateX(100px);
}
Units
可以的話,使用無單位屬性值,如果使用相對單位,更青睞于‘rem’,秒好于毫秒。
/* bad */
div {
margin: 0px;
font-size: .9em;
line-height: 22px;
transition: 500ms;
}
/* good */
div {
margin: 0;
font-size: .9rem;
line-height: 1.5;
transition: .5s;
}
Colors(顏色)
如果你需要透明效果,使用rgba”。否則,總是使用十六進(jìn)制格式。
/* bad */
div {
color: hsl(103, 54%, 43%);
}
/* good */
div {
color: #5a3;
}
Drawing(繪)
當(dāng)資源容易用css代替的話,避免HTTP請求
/* bad */
div::before {
content: url(white-circle.svg);
}
/* good */
div::before {
content: "";
display: block;
width: 20px;
height: 20px;
border-radius: 50%;
background: #fff;
}
Hacks
不要使用它們。
/* bad */
div {
// position: relative;
transform: translateZ(0);
}
/* good */
div {
/* position: relative; */
will-change: transform;
}
JavaScript
Performance(性能)
可讀性、正確性和表現(xiàn)性比性能更重要,JavaScript基本上永遠(yuǎn)不會(huì)成為你的性能瓶頸,優(yōu)化一些東西,像圖像壓縮、網(wǎng)絡(luò)訪問,而不是DOM回流。如果你還記得一個(gè)指導(dǎo)方針從這個(gè)文檔,選擇這一個(gè)。
// bad (albeit way faster)
const arr = [1, 2, 3, 4];
const len = arr.length;
var i = -1;
var result = [];
while (++i < len) {
var n = arr[i];
if (n % 2 > 0) continue;
result.push(n * n);
}
// good
const arr = [1, 2, 3, 4];
const isEven = n => n % 2 == 0;
const square = n => n * n;
const result = arr.filter(isEven).map(square);
Statelessness
盡量保持你函數(shù)的純凈. 所有的功能都應(yīng)該沒有產(chǎn)生其他副作用,使用沒有外部數(shù)據(jù)并返回新對象而不是改變現(xiàn)有的。
// bad
const merge = (target, ...sources) => Object.assign(target, ...sources);
merge({ foo: "foo" }, { bar: "bar" }); // => { foo: "foo", bar: "bar" }
// good
const merge = (...sources) => Object.assign({}, ...sources);
merge({ foo: "foo" }, { bar: "bar" }); // => { foo: "foo", bar: "bar" }
Natives
盡可能使用原生的方法。
// bad
const toArray = obj => [].slice.call(obj);
// good
const toArray = (() =>
Array.from ? Array.from : obj => [].slice.call(obj)
)();
Coercion
Embrace implicit coercion when it makes sense. Avoid it otherwise. Don't cargo-cult.
// bad
if (x === undefined || x === null) { ... }
// good
if (x == undefined) { ... }
Loops
Don't use loops as they force you to use mutable objects. Rely on array.prototype methods.
不要使用循環(huán),如果他們強(qiáng)迫你使用可變的對象。依賴array.prototype方法。
// bad
const sum = arr => {
var sum = 0;
var i = -1;
for (;arr[++i];) {
sum += arr[i];
}
return sum;
};
sum([1, 2, 3]); // => 6
// good
const sum = arr =>
arr.reduce((x, y) => x + y);
sum([1, 2, 3]); // => 6
如果你不能,或者如果使用array.prototype被認(rèn)為是濫用的,那么使用遞歸。
// bad
const createDivs = howMany => {
while (howMany--) {
document.body.insertAdjacentHTML("beforeend", "<div></div>");
}
};
createDivs(5);
// bad
const createDivs = howMany =>
[...Array(howMany)].forEach(() =>
document.body.insertAdjacentHTML("beforeend", "<div></div>")
);
createDivs(5);
// good
const createDivs = howMany => {
if (!howMany) return;
document.body.insertAdjacentHTML("beforeend", "<div></div>");
return createDivs(howMany - 1);
};
createDivs(5);
Arguments
忘記 arguments 對象, rest參數(shù)是更好地選擇,因?yàn)?
- 他的名字更容易讓你知道該函數(shù)所希望的參數(shù)是什么。
- 這是一個(gè)真正的數(shù)組, 更容易使用.
// bad
const sortNumbers = () =>
Array.prototype.slice.call(arguments).sort();
// good
const sortNumbers = (...numbers) => numbers.sort();
Apply
忘記 apply(). 使用擴(kuò)展運(yùn)算符代替。
const greet = (first, last) => `Hi ${first} ${last}`;
const person = ["John", "Doe"];
// bad
greet.apply(null, person);
// good
greet(...person);
Bind
不要使用bind() 當(dāng)有更好的方法時(shí).
// bad
["foo", "bar"].forEach(func.bind(this));
// good
["foo", "bar"].forEach(func, this);
// bad
const person = {
first: "John",
last: "Doe",
greet() {
const full = function() {
return `${this.first} ${this.last}`;
}.bind(this);
return `Hello ${full()}`;
}
}
// good
const person = {
first: "John",
last: "Doe",
greet() {
const full = () => `${this.first} ${this.last}`;
return `Hello ${full()}`;
}
}
Higher-order functions(高階函數(shù))
不要嵌套函數(shù),當(dāng)非必要時(shí)
// bad
[1, 2, 3].map(num => String(num));
// good
[1, 2, 3].map(String);
Composition
Avoid multiple nested function calls. Use composition instead.
避免調(diào)用多個(gè)嵌套函數(shù)。使用組合代替。
const plus1 = a => a + 1;
const mult2 = a => a * 2;
// bad
mult2(plus1(5)); // => 12
// good
const pipeline = (...funcs) => val => funcs.reduce((a, b) => b(a), val);
const addThenMult = pipeline(plus1, mult2);
addThenMult(5); // => 12
Caching
緩存功能測試、大數(shù)據(jù)結(jié)構(gòu)和復(fù)雜的操作
// bad
const contains = (arr, value) =>
Array.prototype.includes
? arr.includes(value)
: arr.some(el => el === value);
contains(["foo", "bar"], "baz"); // => false
// good
const contains = (() =>
Array.prototype.includes
? (arr, value) => arr.includes(value)
: (arr, value) => arr.some(el => el === value)
)();
contains(["foo", "bar"], "baz"); // => false
Variables(變量)
使用 const 好于 let ,而 let 好于 var.
// bad
var me = new Map();
me.set("name", "Ben").set("country", "Belgium");
// good
const me = new Map();
me.set("name", "Ben").set("country", "Belgium");
Conditions(條件)
用IIFE's來返回語句好于if, else if, else 和switch 語句.
// bad
var grade;
if (result < 50)
grade = "bad";
else if (result < 90)
grade = "good";
else
grade = "excellent";
// good
const grade = (() => {
if (result < 50)
return "bad";
if (result < 90)
return "good";
return "excellent";
})();
Object iteration
盡可能避免使用for...in 。
const shared = { foo: "foo" };
const obj = Object.create(shared, {
bar: {
value: "bar",
enumerable: true
}
});
// bad
for (var prop in obj) {
if (obj.hasOwnProperty(prop))
console.log(prop);
}
// good
Object.keys(obj).forEach(prop => console.log(prop));
Objects as Maps
當(dāng)對象合法使用情況下,maps通常是一個(gè)更好的,更強(qiáng)大的選擇。有困惑時(shí),請使用一個(gè)“Map”。
// bad
const me = {
name: "Ben",
age: 30
};
var meSize = Object.keys(me).length;
meSize; // => 2
me.country = "Belgium";
meSize++;
meSize; // => 3
// good
const me = new Map();
me.set("name", "Ben");
me.set("age", 30);
me.size; // => 2
me.set("country", "Belgium");
me.size; // => 3
Curry
Currying 是一個(gè)非常強(qiáng)大的但對于很多開發(fā)者來說卻很陌生的范式. 不要濫用它,但合理地使用它卻往往給人意想不到的效果
// bad
const sum = a => b => a + b;
sum(5)(3); // => 8
// good
const sum = (a, b) => a + b;
sum(5, 3); // => 8
Readability
不要通過看似聰明的技巧混淆代碼的意圖。
// bad
foo || doSomething();
// good
if (!foo) doSomething();
// bad
void function() { /* IIFE */ }();
// good
(function() { /* IIFE */ }());
// bad
const n = ~~3.14;
// good
const n = Math.floor(3.14);
Code reuse
不要害怕去創(chuàng)建很多小的、高度可組合的、可重用的功能。
// bad
arr[arr.length - 1];
// good
const first = arr => arr[0];
const last = arr => first(arr.slice(-1));
last(arr);
// bad
const product = (a, b) => a * b;
const triple = n => n * 3;
// good
const product = (a, b) => a * b;
const triple = product.bind(null, 3);
Dependencies
減少依賴關(guān)系,第三方代碼你不知道,不要為了幾個(gè)容易復(fù)制的方法而去加載一整個(gè)庫。
// bad
var _ = require("underscore");
_.compact(["foo", 0]));
_.unique(["foo", "foo"]);
_.union(["foo"], ["bar"], ["foo"]);
// good
const compact = arr => arr.filter(el => el);
const unique = arr => [...Set(arr)];
const union = (...arr) => unique([].concat(...arr));
compact(["foo", 0]);
unique(["foo", "foo"]);
union(["foo"], ["bar"], ["foo"]);