HTML
語義
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>
簡潔
保持代碼的簡潔。忘記原來的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=[email protected] 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=[email protected] required>
</label>
<script src=main.js></script>
</html>
Accessibility
可訪問性不應該是以後再想的事情。提高網站不需要你成爲一個WCAG專家,你完全可以通過修復一些小問題,從而造成一個巨大的變化,例如:
- 學習正確使用alt 屬性
- 確保鏈接和按鈕被同樣地標記 (不允許
<div class=button>
) - 不專門依靠顏色來傳遞信息
- 明確標註表單控件
<!-- bad -->
<h1><img alt="Logo" src="logo.png"></h1>
<!-- good -->
<h1><img alt="My Company, Inc." src="logo.png"></h1>
語言
當定義語言和字符編碼是可選擇的時候,總是建議在文檔級別同時聲明,即使它們在你的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>
性能
除非有正當理由才能在內容前加載腳本,不要阻塞頁面的渲染。如果你的樣式表很重,開頭就孤立那些絕對需要得樣式,並在一個單獨的樣式表中推遲二次聲明的加載。兩個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
分號
雖然分號在技術上是CSS一個分隔符,但應該始終把它作爲一個終止符。
/* bad */
div {
color: red
}
/* good */
div {
color: red;
}
盒子模型
盒子模型對於整個文檔而言最好是相同的。全局性的* { box-sizing: border-box; }就非常不錯,但是不要改變默認盒子模型的特定元素,如果可以避免的話。
/* bad */
div {
width: 100%;
padding: 10px;
box-sizing: border-box;
}
/* good */
div {
padding: 10px;
}
流
不要更改元素的默認行爲,如果可以避免的話。元素儘可能地保持在自然的文檔流中。例如,刪除圖像下方的空格而不改變其默認顯示:
/* bad */
img {
display: block;
}
/* good */
img {
vertical-align: middle;
}
同樣,如果可以避免的話,不要關閉元素流。
/* bad */
div {
width: 100px;
position: absolute;
right: 0;
}
/* good */
div {
width: 100px;
margin-left: auto;
}
定位
在CSS中有許多定位元素的方法,但應該儘量限制以下屬性/值。按優先順序排列:
display: block;
display: flex;
position: relative;
position: sticky;
position: absolute;
position: fixed;
選擇器
最小化緊密耦合到DOM的選擇器。當選擇器有多於3個結構僞類,後代或兄弟選擇器的時候,考慮添加一個類到你想匹配的元素。
/* bad */
div:first-of-type :last-child > p ~ *
/* good */
div:first-of-type .info
當你不需要的時候避免過載選擇器。
/* 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;
}
覆蓋
覆蓋樣式使得選擇器和調試變得困難。如果可能的話,避免覆蓋樣式。
/* bad */
li {
visibility: hidden;
}
li:first-child {
visibility: visible;
}
/* good */
li + li {
visibility: hidden;
}
繼承
不要重複可以繼承的樣式聲明。
/* bad */
div h1, div p {
text-shadow: 0 1px 0 #fff;
}
/* good */
div {
text-shadow: 0 1px 0 #fff;
}
簡潔
保持代碼的簡潔。使用簡寫屬性,沒有必要的話,要避免使用多個屬性。
/* 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;
}
語言
英語表達優於數學公式。
/* bad */
:nth-child(2n + 1) {
transform: rotate(360deg);
}
/* good */
:nth-child(odd) {
transform: rotate(1turn);
}
瀏覽器引擎前綴
果斷地刪除過時的瀏覽器引擎前綴。如果需要使用的話,可以在標準屬性前插入它們。
/* 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;
}
動畫
視圖轉換優於動畫。除了opacity
和transform
,避免動畫其他屬性。
/* bad */
div:hover {
animation: move 1s forwards;
}
@keyframes move {
100% {
margin-left: 100px;
}
}
/* good */
div:hover {
transition: 1s;
transform: translateX(100px);
}
單位
可以的話,使用無單位的值。如果使用相對單位,那就用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;
}
顏色
如果你需要透明度,使用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
不要使用 hacks
。
/* bad */
div {
// position: relative;
transform: translateZ(0);
}
/* good */
div {
/* position: relative; */
will-change: transform;
}
JavaScript
性能
可讀性,正確性和可表達性優於性能。JavaScript基本上永遠不會是你的性能瓶頸。圖像壓縮,網絡接入和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);
無狀態
儘量保持函數純潔。理論上,所有函數都不會產生副作用,不會使用外部數據,並且會返回新對象,而不是改變現有的對象。
// 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)
)();
強制性
如果強制有意義,那麼就使用隱式強制。否則就應該避免強制。
// bad
if (x === undefined || x === null) { ... }
// good
if (x == undefined) { ... }
循環
不要使用循環,因爲它們會強迫你使用可變對象。依靠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 對象。餘下的參數往往是一個更好的選擇,這是因爲:
你可以從它的命名中更好地瞭解函數需要什麼樣的參數
真實數組,更易於使用。
// 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()
。
// 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()}`;
}
}
嵌套函數
沒有必要的話,就不要嵌套函數。
// bad
[1, 2, 3].map(num => String(num));
// good
[1, 2, 3].map(String);
合成函數
避免調用多重嵌套函數。使用合成函數來替代。
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
緩存
緩存功能測試,大數據結構和任何奢侈的操作。
// 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
優於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");
條件
IIFE
和return
語句優於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";
})();
對象迭代
如果可以的話,避免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對象
在對象有合法用例的情況下,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
Curry雖然功能強大,但對於許多開發人員來說是一個外來的範式。不要濫用,因爲其視情況而定的用例相當不尋常。
// 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);
代碼重用
不要害怕創建小型的,高度可組合的,可重複使用的函數。
// 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);
依賴性
最小化依賴性。第三方是你不知道的代碼。不要只是因爲幾個可輕易複製的方法而加載整個庫:
// 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"]);