项目作者: merrier

项目描述 :
【译文】一些HTML,CSS和JS的最佳实践。
高级语言:
项目地址: git://github.com/merrier/frontend-guidelines-cn.git
创建时间: 2018-08-24T09:33:11Z
项目社区:https://github.com/merrier/frontend-guidelines-cn

开源协议:MIT License

关键词:
frontend guidelines

下载


frontend-guidelines-cn

一些HTML,CSS和JS的最佳实践。翻译自bendc的front-guidelines,同时添加了目录和自己的认识。

目录

HTML

语义化(Semantics)

HTML5为我们提供了大量的语义元素,旨在精确地描述内容。请充分利用这些新的元素。

注:在使用时需要注意兼容性以及这些元素的默认样式

  1. <!-- bad -->
  2. <div id=main>
  3. <div class=article>
  4. <div class=header>
  5. <h1>Blog post</h1>
  6. <p>Published: <span>21st Feb, 2015</span></p>
  7. </div>
  8. <p></p>
  9. </div>
  10. </div>
  11. <!-- good -->
  12. <main>
  13. <article>
  14. <header>
  15. <h1>Blog post</h1>
  16. <p>Published: <time datetime=2015-02-21>21st Feb, 2015</time></p>
  17. </header>
  18. <p></p>
  19. </article>
  20. </main>

确保你理解你使用的H5元素的语义。如果错误的使用,反而还不如使用传统元素。

  1. <!-- bad -->
  2. <h1>
  3. <figure>
  4. <img alt=Company src=logo.png>
  5. </figure>
  6. </h1>
  7. <!-- good -->
  8. <h1>
  9. <img alt=Company src=logo.png>
  10. </h1>

简洁(Brevity)

保持代码简洁。忘掉你之前写XHTML时养成的习惯。

  1. <!-- bad -->
  2. <!doctype html>
  3. <html lang=en>
  4. <head>
  5. <meta http-equiv=Content-Type content="text/html; charset=utf-8" />
  6. <title>Contact</title>
  7. <link rel=stylesheet href=style.css type=text/css />
  8. </head>
  9. <body>
  10. <h1>Contact me</h1>
  11. <label>
  12. Email address:
  13. <input type=email placeholder=you@email.com required=required />
  14. </label>
  15. <script src=main.js type=text/javascript></script>
  16. </body>
  17. </html>
  18. <!-- good -->
  19. <!doctype html>
  20. <html lang=en>
  21. <meta charset=utf-8>
  22. <title>Contact</title>
  23. <link rel=stylesheet href=style.css>
  24. <h1>Contact me</h1>
  25. <label>
  26. Email address:
  27. <input type=email placeholder=you@email.com required>
  28. </label>
  29. <script src=main.js></script>
  30. </html>

可读性(Accessibility)

可访问性应该提前考虑到。你不必为了改进你的网站而成为WCAG专家,你现在可以做一些小的优化,但是它们会带来显著的变化,比如:

  • 正确使用 alt 属性
  • 确保用正确的元素来标记链接和按钮(千万不要用<div class=button>来标记按钮或链接)
  • 不完全依赖颜色来传达信息
  • 显式标注表单控件(即使用label
  1. <!-- bad -->
  2. <h1><img alt=Logo src=logo.png></h1>
  3. <!-- good -->
  4. <h1><img alt=Company src=logo.png></h1>

语言(Language)

虽然语言和字符编码的设置是可选的,但建议始终在HTML中声明,即使它们已经在HTTP报头中指定了。同时,UTF-8比任何其他字符编码都要好。

  1. <!-- bad -->
  2. <!doctype html>
  3. <title>Hello, world.</title>
  4. <!-- good -->
  5. <!doctype html>
  6. <html lang=en>
  7. <meta charset=utf-8>
  8. <title>Hello, world.</title>
  9. </html>

性能(Performance)

如果没有必须在您的内容之前加载脚本的理由,千万不要阻塞页面的呈现。
如果样式比较多(即样式文件比较大),就将那些需要最先使用的样式孤立出来并优先加载,而其他样式可以放在单独的文件中并延迟加载。
两个HTTP请求会明显慢于一个,所以尽量减少HTTP请求。

  1. <!-- bad -->
  2. <!doctype html>
  3. <meta charset=utf-8>
  4. <script src=analytics.js></script>
  5. <title>Hello, world.</title>
  6. <p>...</p>
  7. <!-- good -->
  8. <!doctype html>
  9. <meta charset=utf-8>
  10. <title>Hello, world.</title>
  11. <p>...</p>
  12. <script src=analytics.js></script>

CSS

分号(Semicolons)

语法上讲,分号是CSS中的分隔符,所以总是把它当作终止符来使用(不要省略分号)。

  1. /* bad */
  2. div {
  3. color: red
  4. }
  5. /* good */
  6. div {
  7. color: red;
  8. }

盒模型(Box model)

盒子模型对于整个document应该是一致的。
* { box-sizing: border-box; }无伤大雅,如果可以避免,最好不要更改个别元素的盒模型表现。

  1. /* bad */
  2. div {
  3. width: 100%;
  4. padding: 10px;
  5. box-sizing: border-box;
  6. }
  7. /* good */
  8. div {
  9. padding: 10px;
  10. }

流布局(Flow)

如果可以避免,不要更改元素的默认行为。尽可能让元素保持在自然文档流中。例如,如果你只是想删除图片下面的空白,是不需要改变它的diaplay属性的:

  1. /* bad */
  2. img {
  3. display: block;
  4. }
  5. /* good */
  6. img {
  7. vertical-align: middle;
  8. }

同样的,避免让某个元素脱离正常文档流。

  1. /* bad */
  2. div {
  3. width: 100px;
  4. position: absolute;
  5. right: 0;
  6. }
  7. /* good */
  8. div {
  9. width: 100px;
  10. margin-left: auto;
  11. }

position属性(Positioning)

在CSS中改变元素的定位有很多方法。推荐使用像FlexboxGrid这样的现代布局规范,这样可以避免将元素从正常文档流中移除,例如position: absolute

选择器(Selectors)

简化选择器。当选择器中超过3个结构伪类、子类或兄弟组合时,就应该考虑向要匹配的元素添加类名来简化了。

  1. /* bad */
  2. div:first-of-type :last-child > p ~ *
  3. /* good */
  4. div:first-of-type .info

避免不必要的选择器。

  1. /* bad */
  2. img[src$=svg], ul > li:first-child {
  3. opacity: 0;
  4. }
  5. /* good */
  6. [src$=svg], ul > :first-child {
  7. opacity: 0;
  8. }

易覆盖(Specificity)

不要让选择器难以被覆盖,所以尽量减少id!important的使用。

  1. /* bad */
  2. .bar {
  3. color: green !important;
  4. }
  5. .foo {
  6. color: red;
  7. }
  8. /* good */
  9. .foo.bar {
  10. color: green;
  11. }
  12. .foo {
  13. color: red;
  14. }

避免覆盖(Overriding)

覆盖样式会使样式的调试变困难,同时可读性变差,应该尽量避免。

  1. /* bad */
  2. li {
  3. visibility: hidden;
  4. }
  5. li:first-child {
  6. visibility: visible;
  7. }
  8. /* good */
  9. li + li {
  10. visibility: hidden;
  11. }

继承(Inheritance)

有些样式会自动继承,要合理利用这一特性来简化选择器。

  1. /* bad */
  2. div h1, div p {
  3. text-shadow: 0 1px 0 #fff;
  4. }
  5. /* good */
  6. div {
  7. text-shadow: 0 1px 0 #fff;
  8. }

合并样式(Brevity)

保持代码简洁,尝试合并多个属性。

  1. /* bad */
  2. div {
  3. transition: all 1s;
  4. top: 50%;
  5. margin-top: -10px;
  6. padding-top: 5px;
  7. padding-right: 10px;
  8. padding-bottom: 20px;
  9. padding-left: 10px;
  10. }
  11. /* good */
  12. div {
  13. transition: 1s;
  14. top: calc(50% - 10px);
  15. padding: 5px 10px 20px;
  16. }

语言(Language)

在表示旋转角度时,推荐使用英文的“圈数”(turn),会比角度(deg)更具语义化

  1. /* bad */
  2. :nth-child(2n + 1) {
  3. transform: rotate(360deg);
  4. }
  5. /* good */
  6. :nth-child(odd) {
  7. transform: rotate(1turn);
  8. }

浏览器前缀(Vendor prefixes)

有些浏览器前缀已经过时了,不要继续使用了,而如果真的需要添加前缀,请插在标准属性之前。

  1. /* bad */
  2. div {
  3. transform: scale(2);
  4. -webkit-transform: scale(2);
  5. -moz-transform: scale(2);
  6. -ms-transform: scale(2);
  7. transition: 1s;
  8. -webkit-transition: 1s;
  9. -moz-transition: 1s;
  10. -ms-transition: 1s;
  11. }
  12. /* good */
  13. div {
  14. -webkit-transform: scale(2);
  15. transform: scale(2);
  16. transition: 1s;
  17. }

动画(Animations)

有利于动画的过渡。避免动画比“不透明”和“变换”其他属性。

相比动画,CSS3中的trasition更推荐使用,但是避免对除opacitytransform之外的属性进行动画。

  1. /* bad */
  2. div:hover {
  3. animation: move 1s forwards;
  4. }
  5. @keyframes move {
  6. 100% {
  7. margin-left: 100px;
  8. }
  9. }
  10. /* good */
  11. div:hover {
  12. transition: 1s;
  13. transform: translateX(100px);
  14. }

单位(Units)

尽可能使用纯数字来表示单位。如果使用相对的单位,推荐使用rem。秒要比毫秒更好。

  1. /* bad */
  2. div {
  3. margin: 0px;
  4. font-size: .9em;
  5. line-height: 22px;
  6. transition: 500ms;
  7. }
  8. /* good */
  9. div {
  10. margin: 0;
  11. font-size: .9rem;
  12. line-height: 1.5;
  13. transition: .5s;
  14. }

颜色(Colors)

如果需要透明度,推荐使用rgba。否则,总是使用十六进制格式来表示颜色。

  1. /* bad */
  2. div {
  3. color: hsl(103, 54%, 43%);
  4. }
  5. /* good */
  6. div {
  7. color: #5a3;
  8. }

避免HTTP请求(Drawing)

如果可以用CSS实现某个效果时,避免使用图片,这样可以避免不必要的HTTP请求。

  1. /* bad */
  2. div::before {
  3. content: url(white-circle.svg);
  4. }
  5. /* good */
  6. div::before {
  7. content: "";
  8. display: block;
  9. width: 20px;
  10. height: 20px;
  11. border-radius: 50%;
  12. background: #fff;
  13. }

慎用hack(Hacks)

慎用Hack。

  1. /* bad */
  2. div {
  3. // position: relative;
  4. transform: translateZ(0);
  5. }
  6. /* good */
  7. div {
  8. /* position: relative; */
  9. will-change: transform;
  10. }

JavaScript

性能(Performance)

对可读性、正确性和表现性的要求会高于性能。JavaScript这门语言本身永远不会成为你的性能瓶颈。一些像图片压缩、减少HTTP请求和避免DOM重绘之类的优化方式会对性能产生很大的影响。

  1. // bad (albeit way faster)
  2. const arr = [1, 2, 3, 4];
  3. const len = arr.length;
  4. var i = -1;
  5. var result = [];
  6. while (++i < len) {
  7. var n = arr[i];
  8. if (n % 2 > 0) continue;
  9. result.push(n * n);
  10. }
  11. // good
  12. const arr = [1, 2, 3, 4];
  13. const isEven = n => n % 2 == 0;
  14. const square = n => n * n;
  15. const result = arr.filter(isEven).map(square);

无状态(Statelessness)

尽量保持你的函数纯净。理想情况下,所有的函数都应该不产生副作用,不使用外部数据,并返回新的对象,而不改变现有的对象。

  1. // bad
  2. const merge = (target, ...sources) => Object.assign(target, ...sources);
  3. merge({ foo: "foo" }, { bar: "bar" }); // => { foo: "foo", bar: "bar" }
  4. // good
  5. const merge = (...sources) => Object.assign({}, ...sources);
  6. merge({ foo: "foo" }, { bar: "bar" }); // => { foo: "foo", bar: "bar" }

原生(Natives)

尽可能地用原生提供的方法

  1. // bad
  2. const toArray = obj => [].slice.call(obj);
  3. // good
  4. const toArray = (() =>
  5. Array.from ? Array.from : obj => [].slice.call(obj)
  6. )();

类型转换(Coercion)

有时候隐式类型转换会带来方便,所以不用刻意追求===

  1. // bad
  2. if (x === undefined || x === null) { ... }
  3. // good
  4. if (x == undefined) { ... }

循环(Loops)

不要使用循环,因为它们会强迫你使用可变对象。推荐使用array.prototype原型方法。

  1. // bad
  2. const sum = arr => {
  3. var sum = 0;
  4. var i = -1;
  5. for (;arr[++i];) {
  6. sum += arr[i];
  7. }
  8. return sum;
  9. };
  10. sum([1, 2, 3]); // => 6
  11. // good
  12. const sum = arr =>
  13. arr.reduce((x, y) => x + y);
  14. sum([1, 2, 3]); // => 6

如果你真的没办法避免循环,或者没办法使用array.prototype原型方法,那么推荐使用递归。

  1. // bad
  2. const createDivs = howMany => {
  3. while (howMany--) {
  4. document.body.insertAdjacentHTML("beforeend", "<div></div>");
  5. }
  6. };
  7. createDivs(5);
  8. // bad
  9. const createDivs = howMany =>
  10. [...Array(howMany)].forEach(() =>
  11. document.body.insertAdjacentHTML("beforeend", "<div></div>")
  12. );
  13. createDivs(5);
  14. // good
  15. const createDivs = howMany => {
  16. if (!howMany) return;
  17. document.body.insertAdjacentHTML("beforeend", "<div></div>");
  18. return createDivs(howMany - 1);
  19. };
  20. createDivs(5);

这里有一个泛型循环函数示例,它可以让递归变得更容易使用。

慎用argument(Arguments)

忘掉arguments对象。REST参数总是更好的选择,因为:

1。它不是匿名的,所以它可以让你更好地了解函数所期望的参数。
2。它是一个真正的数组,这使得它更容易使用。

  1. // bad
  2. const sortNumbers = () =>
  3. Array.prototype.slice.call(arguments).sort();
  4. // good
  5. const sortNumbers = (...numbers) => numbers.sort();

慎用apply(Apply)

避免使用apply(),推荐使用扩展运算符。

  1. const greet = (first, last) => `Hi ${first} ${last}`;
  2. const person = ["John", "Doe"];
  3. // bad
  4. greet.apply(null, person);
  5. // good
  6. greet(...person);

慎用bind(Bind)

避免使用bind()

  1. // bad
  2. ["foo", "bar"].forEach(func.bind(this));
  3. // good
  4. ["foo", "bar"].forEach(func, this);
  1. // bad
  2. const person = {
  3. first: "John",
  4. last: "Doe",
  5. greet() {
  6. const full = function() {
  7. return `${this.first} ${this.last}`;
  8. }.bind(this);
  9. return `Hello ${full()}`;
  10. }
  11. }
  12. // good
  13. const person = {
  14. first: "John",
  15. last: "Doe",
  16. greet() {
  17. const full = () => `${this.first} ${this.last}`;
  18. return `Hello ${full()}`;
  19. }
  20. }

避免嵌套(Higher-order functions)

避免函数嵌套。

  1. // bad
  2. [1, 2, 3].map(num => String(num));
  3. // good
  4. [1, 2, 3].map(String);

避免多层嵌套(Composition)

避免多个函数嵌套调用。

Avoid multiple nested function calls. Use composition instead.

  1. const plus1 = a => a + 1;
  2. const mult2 = a => a * 2;
  3. // bad
  4. mult2(plus1(5)); // => 12
  5. // good
  6. const pipeline = (...funcs) => val => funcs.reduce((a, b) => b(a), val);
  7. const addThenMult = pipeline(plus1, mult2);
  8. addThenMult(5); // => 12

缓存(Caching)

对比较大的数据结构和影响性能的操作进行缓存。

  1. // bad
  2. const contains = (arr, value) =>
  3. Array.prototype.includes
  4. ? arr.includes(value)
  5. : arr.some(el => el === value);
  6. contains(["foo", "bar"], "baz"); // => false
  7. // good
  8. const contains = (() =>
  9. Array.prototype.includes
  10. ? (arr, value) => arr.includes(value)
  11. : (arr, value) => arr.some(el => el === value)
  12. )();
  13. contains(["foo", "bar"], "baz"); // => false

变量(Variables)

在变量声明的使用上,const > let > var

  1. // bad
  2. var me = new Map();
  3. me.set("name", "Ben").set("country", "Belgium");
  4. // good
  5. const me = new Map();
  6. me.set("name", "Ben").set("country", "Belgium");

IIFE(Conditions)

推荐使用立即执行函数(IIFE),return语句要优于ifelse ifelseswitch语句。

  1. // bad
  2. var grade;
  3. if (result < 50)
  4. grade = "bad";
  5. else if (result < 90)
  6. grade = "good";
  7. else
  8. grade = "excellent";
  9. // good
  10. const grade = (() => {
  11. if (result < 50)
  12. return "bad";
  13. if (result < 90)
  14. return "good";
  15. return "excellent";
  16. })();

对象遍历(Object iteration)

避免使用for...in

  1. const shared = { foo: "foo" };
  2. const obj = Object.create(shared, {
  3. bar: {
  4. value: "bar",
  5. enumerable: true
  6. }
  7. });
  8. // bad
  9. for (var prop in obj) {
  10. if (obj.hasOwnProperty(prop))
  11. console.log(prop);
  12. }
  13. // good
  14. Object.keys(obj).forEach(prop => console.log(prop));

Map(Objects as Maps)

虽然大家已经非常习惯使用Object,但是Map通常是更好的选择。当你不知道哪个更好时,使用Map吧。

  1. // bad
  2. const me = {
  3. name: "Ben",
  4. age: 30
  5. };
  6. var meSize = Object.keys(me).length;
  7. meSize; // => 2
  8. me.country = "Belgium";
  9. meSize++;
  10. meSize; // => 3
  11. // good
  12. const me = new Map();
  13. me.set("name", "Ben");
  14. me.set("age", 30);
  15. me.size; // => 2
  16. me.set("country", "Belgium");
  17. me.size; // => 3

科里化(Curry)

对于许多开发者来说,科里化是一个很强大但是比较陌生的概念,所以不要滥用它。

  1. // bad
  2. const sum = a => b => a + b;
  3. sum(5)(3); // => 8
  4. // good
  5. const sum = (a, b) => a + b;
  6. sum(5, 3); // => 8

可读性(Readability)

不要用看似聪明的技巧来降低代码的可读性。

  1. // bad
  2. foo || doSomething();
  3. // good
  4. if (!foo) doSomething();
  1. // bad
  2. void function() { /* IIFE */ }();
  3. // good
  4. (function() { /* IIFE */ }());
  1. // bad
  2. const n = ~~3.14;
  3. // good
  4. const n = Math.floor(3.14);

代码复用(Code reuse)

不要害怕创建很多小的、高度可组合的和可重用的函数。

  1. // bad
  2. arr[arr.length - 1];
  3. // good
  4. const first = arr => arr[0];
  5. const last = arr => first(arr.slice(-1));
  6. last(arr);
  1. // bad
  2. const product = (a, b) => a * b;
  3. const triple = n => n * 3;
  4. // good
  5. const product = (a, b) => a * b;
  6. const triple = product.bind(null, 3);

最小化依赖(Dependencies)

最小化依赖。你很难知道第三方代码的具体实现逻辑。所以如果你只需要某个库中的有限方法,不要引入整个库。

  1. // bad
  2. var _ = require("underscore");
  3. _.compact(["foo", 0]));
  4. _.unique(["foo", "foo"]);
  5. _.union(["foo"], ["bar"], ["foo"]);
  6. // good
  7. const compact = arr => arr.filter(el => el);
  8. const unique = arr => [...new Set(arr)];
  9. const union = (...arr) => unique([].concat(...arr));
  10. compact(["foo", 0]);
  11. unique(["foo", "foo"]);
  12. union(["foo"], ["bar"], ["foo"]);