最全面的前端開發指南
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></pre>
你需要理解你正在使用的元素的語義。用一種錯誤的方式使用語義元素比保持中立更糟糕。
<!-- bad --> <h1> <figure> <img alt=Company src=logo.png> </figure> </h1><!-- good --> <h1> <img alt=Company src=logo.png> </h1></pre>
簡潔
保持代碼的簡潔。忘記原來的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></pre>
可訪問性
可訪問性不應該是以后再想的事情。提高網站不需要你成為一個WCAG專家,你完全可以通過修復一些小問題,從而造成一個巨大的變化,例如:
- 學習正確使用
alt
屬性 - 確保鏈接和按鈕被同樣地標記(不允許<div>)
- 不專門依靠顏色來傳遞信息
- 明確標注表單控件 </ul>
<!-- bad --> <h1><img alt="Logo" src="logo.png"></h1><!-- good --> <h1><img alt="My Company, Inc." src="logo.png"></h1></pre>
語言
當定義語言和字符編碼是可選擇的時候,總是建議在文檔級別同時聲明,即使它們在你的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></pre>
性能
除非有正當理由才能在內容前加載腳本,不要阻塞頁面的渲染。如果你的樣式表很重,開頭就孤立那些絕對需要得樣式,并在一個單獨的樣式表中推遲二次聲明的加載。兩個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></pre>
CSS
分號
雖然分號在技術上是CSS一個分隔符,但應該始終把它作為一個終止符。
/ bad / div { color: red }/ good / div { color: red; }</pre>
盒子模型
盒子模型對于整個文檔而言最好是相同的。全局性的* { box-sizing: border-box; }就非常不錯,但是不要改變默認盒子模型的特定元素,如果可以避免的話。
/ bad / div { width: 100%; padding: 10px; box-sizing: border-box; }/ good / div { padding: 10px; }</pre>
流
不要更改元素的默認行為,如果可以避免的話。元素盡可能地保持在自然的文檔流中。例如,刪除圖像下方的空格而不改變其默認顯示:
/ bad / img { display: block; }/ good / img { vertical-align: middle; }</pre>
同樣,如果可以避免的話,不要關閉元素流。
/ bad / div { width: 100px; position: absolute; right: 0; }/ good / div { width: 100px; margin-left: auto; }</pre>
定位
在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</pre>
當你不需要的時候避免過載選擇器。
/ bad / img[src$=svg], ul > li:first-child { opacity: 0; }/ good / [src$=svg], ul > :first-child { opacity: 0; }</pre>
特異性
不要讓值和選擇器難以覆蓋。盡量少用id,并避免!important。
/ bad / .bar { color: green !important; } .foo { color: red; }/ good / .foo.bar { color: green; } .foo { color: red; }</pre>
覆蓋
覆蓋樣式使得選擇器和調試變得困難。如果可能的話,避免覆蓋樣式。
/ bad / li { visibility: hidden; } li:first-child { visibility: visible; }/ good / li + li { visibility: hidden; }</pre>
繼承
不要重復可以繼承的樣式聲明。
/ bad / div h1, div p { text-shadow: 0 1px 0 #fff; }/ good / div { text-shadow: 0 1px 0 #fff; }</pre>
簡潔
保持代碼的簡潔。使用簡寫屬性,沒有必要的話,要避免使用多個屬性。
/ 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; }</pre>
語言
英語表達優于數學公式。
/ bad / :nth-child(2n + 1) { transform: rotate(360deg); }/ good / :nth-child(odd) { transform: rotate(1turn); }</pre>
瀏覽器引擎前綴
果斷地刪除過時的瀏覽器引擎前綴。如果需要使用的話,可以在標準屬性前插入它們。
/ 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; }</pre>
動畫
視圖轉換優于動畫。除了
opacity
和transform,避免動畫其他屬性。/ bad / div:hover { animation: move 1s forwards; } @keyframes move { 100% { margin-left: 100px; } }/ good / div:hover { transition: 1s; transform: translateX(100px); }</pre>
單位
可以的話,使用無單位的值。如果使用相對單位,那就用
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; }</pre>
顏色
如果你需要透明度,使用rgba。另外,始終使用十六進制格式。
/ bad / div { color: hsl(103, 54%, 43%); }/ good / div { color: #5a3; }</pre>
繪畫
當資源很容易用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; }</pre>
Hacks
不要使用Hacks。
/ bad / div { // position: relative; transform: translateZ(0); }/ good / div { / position: relative; / will-change: transform; }</pre>
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);</pre>
無狀態
盡量保持函數純潔。理論上,所有函數都不會產生副作用,不會使用外部數據,并且會返回新對象,而不是改變現有的對象。
// 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" }</pre>
本地化
盡可能地依賴本地方法。
// bad const toArray = obj => [].slice.call(obj);// good const toArray = (() => Array.from ? Array.from : obj => [].slice.call(obj) )();</pre>
強制性
如果強制有意義,那么就使用隱式強制。否則就應該避免強制。
// bad if (x === undefined || x === null) { ... }// good if (x == undefined) { ... }</pre>
循環
不要使用循環,因為它們會強迫你使用可變對象。依靠
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</pre>
如果不能避免,或使用
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);</pre>
這里有一個通用的循環功能,可以讓遞歸更容易使用。
參數
忘記
arguments
對象。余下的參數往往是一個更好的選擇,這是因為:你可以從它的命名中更好地了解函數需要什么樣的參數
真實數組,更易于使用。
// bad const sortNumbers = () => Array.prototype.slice.call(arguments).sort();// good const sortNumbers = (...numbers) => numbers.sort();</pre>
應用
忘掉apply()。使用操作符。
const greet = (first, last) =>Hi ${first} ${last}
; const person = ["John", "Doe"];// bad greet.apply(null, person);
// good greet(...person);</pre>
綁定
當有更慣用的做法時,就不要用bind() 。
// bad ["foo", "bar"].forEach(func.bind(this));// good ["foo", "bar"].forEach(func, this);</pre>
// bad const person = { first: "John", last: "Doe", greet() { const full = function() { return${this.first} ${this.last}
; }.bind(this); returnHello ${full()}
; } }// good const person = { first: "John", last: "Doe", greet() { const full = () =>
${this.first} ${this.last}
; returnHello ${full()}
; } }</pre>函數嵌套
沒有必要的話,就不要嵌套函數。
// bad [1, 2, 3].map(num => String(num));// good [1, 2, 3].map(String);</pre>
合成函數
避免調用多重嵌套函數。使用合成函數來替代。
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</pre>
緩存
緩存功能測試,大數據結構和任何奢侈的操作。
// 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</pre>
變量
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");</pre>
條件
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"; })();</pre>
對象迭代
如果可以的話,避免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));</pre>
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</pre>
Curry
Curry雖然功能強大,但對于許多開發人員來說是一個外來的范式。不要濫用,因為其視情況而定的用例相當不尋常。
// bad const sum = a => b => a + b; sum(5)(3); // => 8// good const sum = (a, b) => a + b; sum(5, 3); // => 8</pre>
可讀性
不要用看似聰明的伎倆混淆代碼的意圖。
// bad foo || doSomething();// good if (!foo) doSomething();</pre>
// bad void function() { / IIFE / }();// good (function() { / IIFE / }());</pre>
// bad const n = ~~3.14;// good const n = Math.floor(3.14);</pre>
代碼重用
不要害怕創建小型的,高度可組合的,可重復使用的函數。
// bad arr[arr.length - 1];// good const first = arr => arr[0]; const last = arr => first(arr.slice(-1)); last(arr);</pre>
// 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);</pre>
依賴性
最小化依賴性。第三方是你不知道的代碼。不要只是因為幾個可輕易復制的方法而加載整個庫:
// 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"]);</pre>譯文鏈接:http://www.codeceo.com/article/full-frontend-guidelines.html
英文原文:Frontend Guidelines
翻譯作者:碼農網 – 小峰本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!