譯文鏈接:http://www.codeceo.com/article/full-frontend-guidelines.html
翻譯作者:碼農(nóng)網(wǎng) – 小峰
英文原文:Frontend Guidelines
HTML
語義
HTML5為我們提供了很多旨在精確描述內(nèi)容的語義元素。確保你可以從它豐富的詞匯中獲益。
<!-- 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ò)誤的方式使用語義元素比保持中立更糟糕。
<!-- bad -->
<h1>
<figure>
<img alt=Company src=logo.png>
</figure>
</h1>
<!-- good -->
<h1>
<img alt=Company src=logo.png>
</h1>
簡潔
保持代碼的簡潔。忘記原來的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>
可訪問性
可訪問性不應(yīng)該是以后再想的事情。提高網(wǎng)站不需要你成為一個(gè)WCAG專家,你完全可以通過修復(fù)一些小問題,從而造成一個(gè)巨大的變化,例如:
- 學(xué)習(xí)正確使用
alt屬性 - 確保鏈接和按鈕被同樣地標(biāo)記(不允許
<div>) - 不專門依靠顏色來傳遞信息
- 明確標(biāo)注表單控件
<!-- bad -->
<h1><img alt="Logo" src="logo.png"></h1>
<!-- good -->
<h1><img alt="My Company, Inc." src="logo.png"></h1>
語言
當(dāng)定義語言和字符編碼是可選擇的時(shí)候,總是建議在文檔級(jí)別同時(shí)聲明,即使它們?cè)谀愕腍TTP標(biāo)頭已經(jīng)詳細(xì)說明。比任何其他字符編碼更偏愛UTF-8。
<!-- bad -->
<!doctype html>
<title>Hello, world.</title>
<!-- good -->
<!doctype html>
<html lang=en>
<meta charset=utf-8>
<title>Hello, world.</title>
</html>
性能
除非有正當(dāng)理由才能在內(nèi)容前加載腳本,不要阻塞頁面的渲染。如果你的樣式表很重,開頭就孤立那些絕對(duì)需要得樣式,并在一個(gè)單獨(dú)的樣式表中推遲二次聲明的加載。兩個(gè)HTTP請(qǐng)求顯然比一個(gè)慢,但是感知速度是最重要的因素。
<!-- 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
分號(hào)
雖然分號(hào)在技術(shù)上是CSS一個(gè)分隔符,但應(yīng)該始終把它作為一個(gè)終止符。
/* bad */
div {
color: red
}
/* good */
div {
color: red;
}
盒子模型
盒子模型對(duì)于整個(gè)文檔而言最好是相同的。全局性的* { box-sizing: border-box; }就非常不錯(cuò),但是不要改變默認(rèn)盒子模型的特定元素,如果可以避免的話。
/* bad */
div {
width: 100%;
padding: 10px;
box-sizing: border-box;
}
/* good */
div {
padding: 10px;
}
流
不要更改元素的默認(rèn)行為,如果可以避免的話。元素盡可能地保持在自然的文檔流中。例如,刪除圖像下方的空格而不改變其默認(rèn)顯示:
/* bad */
img {
display: block;
}
/* good */
img {
vertical-align: middle;
}
同樣,如果可以避免的話,不要關(guān)閉元素流。
/* bad */
div {
width: 100px;
position: absolute;
right: 0;
}
/* good */
div {
width: 100px;
margin-left: auto;
}
定位
在CSS中有許多定位元素的方法,但應(yīng)該盡量限制以下屬性/值。按優(yōu)先順序排列:
display: block;
display: flex;
position: relative;
position: sticky;
position: absolute;
position: fixed;
選擇器
最小化緊密耦合到DOM的選擇器。當(dāng)選擇器有多于3個(gè)結(jié)構(gòu)偽類,后代或兄弟選擇器的時(shí)候,考慮添加一個(gè)類到你想匹配的元素。
/* bad */
div:first-of-type :last-child > p ~ *
/* good */
div:first-of-type .info
當(dāng)你不需要的時(shí)候避免過載選擇器。
/* bad */
img[src$=svg], ul > li:first-child {
opacity: 0;
}
/* good */
[src$=svg], ul > :first-child {
opacity: 0;
}
特異性
不要讓值和選擇器難以覆蓋。盡量少用id,并避免!important。
/* bad */
.bar {
color: green !important;
}
.foo {
color: red;
}
/* good */
.foo.bar {
color: green;
}
.foo {
color: red;
}
覆蓋
覆蓋樣式使得選擇器和調(diào)試變得困難。如果可能的話,避免覆蓋樣式。
/* bad */
li {
visibility: hidden;
}
li:first-child {
visibility: visible;
}
/* good */
li + li {
visibility: hidden;
}
繼承
不要重復(fù)可以繼承的樣式聲明。
/* bad */
div h1, div p {
text-shadow: 0 1px 0 #fff;
}
/* good */
div {
text-shadow: 0 1px 0 #fff;
}
簡潔
保持代碼的簡潔。使用簡寫屬性,沒有必要的話,要避免使用多個(gè)屬性。
/* 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;
}
語言
英語表達(dá)優(yōu)于數(shù)學(xué)公式。
/* bad */
:nth-child(2n + 1) {
transform: rotate(360deg);
}
/* good */
:nth-child(odd) {
transform: rotate(1turn);
}
瀏覽器引擎前綴
果斷地刪除過時(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;
}
動(dòng)畫
視圖轉(zhuǎn)換優(yōu)于動(dòng)畫。除了opacity 和transform,避免動(dòng)畫其他屬性。
/* bad */
div:hover {
animation: move 1s forwards;
}
@keyframes move {
100% {
margin-left: 100px;
}
}
/* good */
div:hover {
transition: 1s;
transform: translateX(100px);
}
單位
可以的話,使用無單位的值。如果使用相對(duì)單位,那就用rem 。秒優(yōu)于毫秒。
/* 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;
}
顏色
如果你需要透明度,使用rgba。另外,始終使用十六進(jìn)制格式。
/* bad */
div {
color: hsl(103, 54%, 43%);
}
/* good */
div {
color: #5a3;
}
繪畫
當(dāng)資源很容易用CSS復(fù)制的時(shí)候,避免HTTP請(qǐng)求。
/* bad */
div::before {
content: url(white-circle.svg);
}
/* good */
div::before {
content: "";
display: block;
width: 20px;
height: 20px;
border-radius: 50%;
background: #fff;
}
Hacks
不要使用Hacks。
/* bad */
div {
// position: relative;
transform: translateZ(0);
}
/* good */
div {
/* position: relative; */
will-change: transform;
}
JavaScript
性能
可讀性,正確性和可表達(dá)性優(yōu)于性能。JavaScript基本上永遠(yuǎn)不會(huì)是你的性能瓶頸。圖像壓縮,網(wǎng)絡(luò)接入和DOM重排來代替優(yōu)化。如果從本文中你只能記住一個(gè)指導(dǎo)原則,那么毫無疑問就是這一條。
// 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);
無狀態(tài)
盡量保持函數(shù)純潔。理論上,所有函數(shù)都不會(huì)產(chǎn)生副作用,不會(huì)使用外部數(shù)據(jù),并且會(huì)返回新對(duì)象,而不是改變現(xiàn)有的對(duì)象。
// 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" }
本地化
盡可能地依賴本地方法。
// bad
const toArray = obj => [].slice.call(obj);
// good
const toArray = (() =>
Array.from ? Array.from : obj => [].slice.call(obj)
)();
強(qiáng)制性
如果強(qiáng)制有意義,那么就使用隱式強(qiáng)制。否則就應(yīng)該避免強(qiáng)制。
// bad
if (x === undefined || x === null) { ... }
// good
if (x == undefined) { ... }
循環(huán)
不要使用循環(huán),因?yàn)樗鼈儠?huì)強(qiáng)迫你使用可變對(duì)象。依靠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);
這里有一個(gè)通用的循環(huán)功能,可以讓遞歸更容易使用。
參數(shù)
忘記arguments 對(duì)象。余下的參數(shù)往往是一個(gè)更好的選擇,這是因?yàn)椋?/p>
你可以從它的命名中更好地了解函數(shù)需要什么樣的參數(shù)
真實(shí)數(shù)組,更易于使用。
// bad
const sortNumbers = () =>
Array.prototype.slice.call(arguments).sort();
// good
const sortNumbers = (...numbers) => numbers.sort();
應(yīng)用
忘掉apply()。使用操作符。
const greet = (first, last) => `Hi ${first} ${last}`;
const person = ["John", "Doe"];
// bad
greet.apply(null, person);
// good
greet(...person);
綁定
當(dāng)有更慣用的做法時(shí),就不要用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()}`;
}
}
函數(shù)嵌套
沒有必要的話,就不要嵌套函數(shù)。
// bad
[1, 2, 3].map(num => String(num));
// good
[1, 2, 3].map(String);
合成函數(shù)
避免調(diào)用多重嵌套函數(shù)。使用合成函數(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
緩存
緩存功能測試,大數(shù)據(jù)結(jié)構(gòu)和任何奢侈的操作。
// 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
變量
const 優(yōu)于let ,let 優(yōu)于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");
條件
IIFE 和return 語句優(yōu)于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";
})();
對(duì)象迭代
如果可以的話,避免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));
map對(duì)象
在對(duì)象有合法用例的情況下,map通常是一個(gè)更好,更強(qiáng)大的選擇。
// 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
Curry雖然功能強(qiáng)大,但對(duì)于許多開發(fā)人員來說是一個(gè)外來的范式。不要濫用,因?yàn)槠湟暻闆r而定的用例相當(dāng)不尋常。
// bad
const sum = a => b => a + b;
sum(5)(3); // => 8
// good
const sum = (a, b) => a + b;
sum(5, 3); // => 8
可讀性
不要用看似聰明的伎倆混淆代碼的意圖。
// 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);
代碼重用
不要害怕創(chuàng)建小型的,高度可組合的,可重復(fù)使用的函數(shù)。
// 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);
依賴性
最小化依賴性。第三方是你不知道的代碼。不要只是因?yà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"]);