Frontend Guidelines
HTML
Semantics(語義化)
為了更精確地描述我們的網頁內容玷禽,HTML5提供了許多語義化標簽渤闷,你應該確保從豐富的詞匯中受益:
<!-- 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>
確保理解你使用的元素的語義省古,錯誤地使用一個語義比不用更糟糕疏唾。
<!-- bad -->
<h1>
<figure>
<img alt=Company src=logo.png>
</figure>
</h1>
<!-- good -->
<h1>
<img alt=Company src=logo.png>
</h1>
Brevity(簡介)
讓你的代碼簡潔。忘記你的舊的XHTML的習慣弧满。
<!-- 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(可訪問性)
可訪問性不是個事后想法勋篓,你不必是一個WCAG專家來改善你的
網站吧享,你可以立即開始通過固定的小東西,達到一個巨大的效果譬嚣,如:
- 學會合理的使用
alt
屬性 - 不是完全依賴顏色來進行信息交流
*顯式標記窗體控件
<!-- 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標頭中指定拜银。在任何其他支持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文件阻止渲染你的頁面。如果你的樣式表是沉重的尼桶,隔離最初的風格絕對必需操灿,并將二次聲明的延遲加載在一個單獨的樣式表中。
兩個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(分號)
當分號是CSS技術上的分離器時,應該總是用它來結束語句幌蚊。
/* bad */
div {
color: red
}
/* good */
div {
color: red;
}
Box model(盒子模型)
盒子模型應該為整個文檔是一樣的谤碳。一個全局的 “* { box-sizing:border-box;}” 是可以的,但,如果你能避免的話溢豆,請不要在特定元素里面改變它的默認盒模型。
/* bad */
div {
width: 100%;
padding: 10px;
box-sizing: border-box;
}
/* good */
div {
padding: 10px;
}
Flow
能避免的話瘸羡,不要改變一個元素的默認行為漩仙。盡可能保持它的自然文本流。例如犹赖,移除圖片下面的空白間隙不應該改變圖片的默認顯示队他。
/* 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的選擇器粘昨。當您的選擇器超過了3個結構的偽類垢啼、后代或兄弟選擇器窜锯,考慮添加一個類到要匹配的元素。
/* 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
覆蓋樣式使選擇器和調試變得困難,盡量避免
/* bad */
li {
visibility: hidden;
}
li:first-child {
visibility: visible;
}
/* good */
li + li {
visibility: hidden;
}
Inheritance
不要重復可以繼承的樣式馁启。
/* bad */
div h1, div p {
text-shadow: 0 1px 0 #fff;
}
/* good */
div {
text-shadow: 0 1px 0 #fff;
}
Brevity(簡潔)
保持你代碼的簡潔性驾孔。使用簡寫屬性,并避免使用多個屬性在非必要時惯疙。
/* 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(語言)
喜歡英語勝過數學翠勉。
/* 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.
不要使用過時的前綴。如果你需要使用它們,把它們插入標準屬性之前霉颠。
/* 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(動畫)
transitions 好于 animations. 避免使opacity
and transform
以外的屬性產生動畫效果.
/* 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”酥郭。否則,總是使用十六進制格式华坦。
/* bad */
div {
color: hsl(103, 54%, 43%);
}
/* good */
div {
color: #5a3;
}
Drawing(繪)
當資源容易用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(性能)
可讀性惜姐、正確性和表現性比性能更重要,JavaScript基本上永遠不會成為你的性能瓶頸椿息,優(yōu)化一些東西歹袁,像圖像壓縮、網絡訪問,而不是DOM回流寝优。如果你還記得一個指導方針從這個文檔,選擇這一個条舔。
// 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
盡量保持你函數的純凈. 所有的功能都應該沒有產生其他副作用,使用沒有外部數據并返回新對象而不是改變現有的。
// 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),如果他們強迫你使用可變的對象孟抗。依賴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
被認為是濫用的凄硼,那么使用遞歸。
// 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參數是更好地選擇摊沉,因為:
- 他的名字更容易讓你知道該函數所希望的參數是什么。
- 這是一個真正的數組, 更容易使用.
// bad
const sortNumbers = () =>
Array.prototype.slice.call(arguments).sort();
// good
const sortNumbers = (...numbers) => numbers.sort();
Apply
忘記 apply()
. 使用擴展運算符代替痒给。
const greet = (first, last) => `Hi ${first} ${last}`;
const person = ["John", "Doe"];
// bad
greet.apply(null, person);
// good
greet(...person);
Bind
不要使用bind()
當有更好的方法時.
// 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(高階函數)
不要嵌套函數说墨,當非必要時
// bad
[1, 2, 3].map(num => String(num));
// good
[1, 2, 3].map(String);
Composition
Avoid multiple nested function calls. Use composition instead.
避免調用多個嵌套函數骏全。使用組合代替。
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
緩存功能測試婉刀、大數據結構和復雜的操作
// 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
當對象合法使用情況下,maps通常是一個更好的,更強大的選擇突颊。有困惑時,請使用一個“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 是一個非常強大的但對于很多開發(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
減少依賴關系糙申,第三方代碼你不知道,不要為了幾個容易復制的方法而去加載一整個庫。
// 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"]);