前端代碼指南
原文 http://www.cnblogs.com/huyong/p/5018380.html
看到一份很受歡迎的 前端代碼指南 ,根據自己的理解進行了翻譯,但能力有限,對一些JS代碼理解不了,如有錯誤,望斧正。
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 class="button">這種粗暴的做法)
- 不依賴于顏色來傳達信息
- 給表單做好lable標記 </ul>
<!-- bad --> <h1><img alt="Logo" src="logo.png"></h1><!-- good --> <h1><img alt="My Company, Inc." src="logo.png"></h1></pre> <h3>語言 </h3>
定義語言和字符編碼是可選項,建議在文檔級別處定義。使用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
分號
不能漏寫分號
/ bad / div { color: red }/ good / div { color: red; }</pre>
盒模型
整個文檔的盒模型應該要相同,最好使用global * { 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選擇器,三個層級以上建議加class:
/ 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>
動畫
除了變形和改變透明度用animation,其他盡量使用transition。
/ bad / div:hover { animation: move 1s forwards; } @keyframes move { 100% { margin-left: 100px; } }/ good / div:hover { transition: 1s; transform: translateX(100px); }</pre>
單位
可以不用單位時就不用。建議用rem。時間單位用s比ms好。
/ 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,否則都用16進制表示:
/ bad / div { color: hsl(103, 54%, 43%); }/ good / div { color: #5a3; }</pre>
繪圖
減少HTTPS請求,盡量用CSS繪圖替代圖片:
/ bad / div::before { content: url(white-circle.svg); }/ good / div::before { content: ""; display: block; width: 20px; height: 20px; border-radius: 50%; background: #fff; }</pre>
注釋
/ 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>
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" }</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 If you can't, or if using array.prototype methods is arguably abusive, use recursion.
// 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
忘記arguments對象吧,其他參數是更好的選擇,因為:
- 它已經被定義
-
它是一個真的數組,很方便使用
// bad const sortNumbers = () => Array.prototype.slice.call(arguments).sort();
// good const sortNumbers = (...numbers) => numbers.sort();</pre></li> </ul>
Apply
忘記apply(),改用運算操作。
const greet = (first, last) =>
Hi ${first} ${last}
; const person = ["John", "Doe"];// bad greet.apply(null, person);
// good greet(...person);</pre>
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); 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>
Composition
避免方法嵌套調用,改用composition:
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 obj = {}; obj"foo" + "bar" = "baz";
// good const obj = {
};</pre>
條件判斷
用多個if,優于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 = Map(); me.set("name", "Ben"); me.set("age", 30); me.size; // => 2 me.set("country", "Belgium"); me.size; // => 3</pre>
Curry
在別的語言里有Curry的一席之地,但在JS里避免使用。不然會是代碼閱讀困難。
// 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();
// bad void function() { / IIFE / }();
// good (function() { / IIFE / }());
// 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);
// 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>
英文原文 Frontend Guidelines
</div>