前端指導性建議

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參數是更好地選擇摊沉,因為:

  1. 他的名字更容易讓你知道該函數所希望的參數是什么。
  2. 這是一個真正的數組, 更容易使用.
// 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"]);
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末船惨,一起剝皮案震驚了整個濱河市柜裸,隨后出現的幾起案子,更是在濱河造成了極大的恐慌粱锐,老刑警劉巖疙挺,帶你破解...
    沈念sama閱讀 216,496評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現場離奇詭異怜浅,居然都是意外死亡铐然,警方通過查閱死者的電腦和手機,發(fā)現死者居然都...
    沈念sama閱讀 92,407評論 3 392
  • 文/潘曉璐 我一進店門恶座,熙熙樓的掌柜王于貴愁眉苦臉地迎上來搀暑,“玉大人,你說我怎么就攤上這事跨琳∽缘悖” “怎么了?”我有些...
    開封第一講書人閱讀 162,632評論 0 353
  • 文/不壞的土叔 我叫張陵脉让,是天一觀的道長樟氢。 經常有香客問我,道長侠鳄,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,180評論 1 292
  • 正文 為了忘掉前任死宣,我火速辦了婚禮伟恶,結果婚禮上,老公的妹妹穿的比我還像新娘毅该。我一直安慰自己博秫,他們只是感情好潦牛,可當我...
    茶點故事閱讀 67,198評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著挡育,像睡著了一般巴碗。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上即寒,一...
    開封第一講書人閱讀 51,165評論 1 299
  • 那天橡淆,我揣著相機與錄音,去河邊找鬼母赵。 笑死逸爵,一個胖子當著我的面吹牛,可吹牛的內容都是我干的凹嘲。 我是一名探鬼主播师倔,決...
    沈念sama閱讀 40,052評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼周蹭!你這毒婦竟也來了趋艘?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 38,910評論 0 274
  • 序言:老撾萬榮一對情侶失蹤凶朗,失蹤者是張志新(化名)和其女友劉穎瓷胧,沒想到半個月后,有當地人在樹林里發(fā)現了一具尸體俱尼,經...
    沈念sama閱讀 45,324評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡抖单,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,542評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現自己被綠了遇八。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片矛绘。...
    茶點故事閱讀 39,711評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖刃永,靈堂內的尸體忽然破棺而出货矮,到底是詐尸還是另有隱情,我是刑警寧澤斯够,帶...
    沈念sama閱讀 35,424評論 5 343
  • 正文 年R本政府宣布囚玫,位于F島的核電站,受9級特大地震影響读规,放射性物質發(fā)生泄漏抓督。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,017評論 3 326
  • 文/蒙蒙 一束亏、第九天 我趴在偏房一處隱蔽的房頂上張望铃在。 院中可真熱鬧,春花似錦、人聲如沸定铜。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽揣炕。三九已至帘皿,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間畸陡,已是汗流浹背鹰溜。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留罩锐,地道東北人奉狈。 一個月前我還...
    沈念sama閱讀 47,722評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像涩惑,于是被迫代替她去往敵國和親仁期。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,611評論 2 353

推薦閱讀更多精彩內容

  • 問答題47 /72 常見瀏覽器兼容性問題與解決方案竭恬? 參考答案 (1)瀏覽器兼容問題一:不同瀏覽器的標簽默認的外補...
    _Yfling閱讀 13,748評論 1 92
  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理跛蛋,服務發(fā)現,斷路器痊硕,智...
    卡卡羅2017閱讀 134,651評論 18 139
  • 在線閱讀 http://interview.poetries.top[http://interview.poetr...
    程序員poetry閱讀 114,359評論 24 450
  • 我自己是一枚閱讀小白赊级,大約從4個月前喜歡上閱讀。 所謂磨刀不誤砍柴工岔绸,在投身到知識的海洋中之前理逊,先學一學如何閱讀,...
    海貝007閱讀 580評論 0 9
  • 飛行到達 我是第一次出國盒揉,并且是自己一個人晋被。第一次從飛機上俯瞰異國的景色,看到飛機下面一片片的樹林刚盈、河流羡洛,一小撮的...
    閆永清exe閱讀 260評論 0 0