项目作者: Go7hic

项目描述 :
一些前端的最佳实践,包括 HTML, CSS, JS
高级语言:
项目地址: git://github.com/Go7hic/front-end-best-practices.git


front-end-best-practices

一些前端的最佳实践,包括 html,css,javascript

HTML

语义

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>

确保你了解你使用的语义元素。错误的使用语义元素是很糟糕的。

  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>

简洁

保持代码简洁。忘记你的旧 XHTM L的习惯。

  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>

可访问性

可访问性不应该是后面再来做的事。但你也不必成为一个WCAG专家来提高你的
网站,你可以立即做一些小事情,就会有巨大的改变,如:

  • 学习正确使用“alt”属性
  • 确保你的链接和按钮等标记(没有“< div class = button”这种滥用)
  • 不完全依赖颜色信息交流
  • 明确 label input控件
  1. <!-- bad -->
  2. <h1><img alt="Logo" src="logo.png"></h1>
  3. <!-- good -->
  4. <h1><img alt="My Company, Inc." src="logo.png"></h1>

语言和字符编码

语言虽然是可选的,但还是推荐在根元素上声明它。

HTML标准要求页面使用UTF-8字符编码。必须声明它,虽然可以在Content-Type HTTP头文件中声明它,但建议始终在文档级别声明它。

  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>

性能

除非有一个充分的理由不然在加载脚本内容之前不要阻止呈现的页面。

  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

分号

分号在技术上是一个分离器,总是把它当作结束符。

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

盒模型

盒子模型应该为整个文档是一样的。一个全局
“* { 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. }

文档流

如果你能避免最好不要改变一个元素的默认行为。尽可能的保持元素
自然文档流。例如,删除图像下的 white-space 不应该让你改变其默认显示:

  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. }

定位

css有很多方法来定位元素,但是最好使用下面的属性/值,按照优先顺序:

  1. display: flex;
  2. display: grid;
  3. display: block;
  4. position: relative;
  5. position: sticky;
  6. position: absolute;
  7. position: fixed;

应该尽量避免从常规文档流中删除元素,例如,使用position:absolute。

选择器

减少选择器紧密耦合的DOM。考虑添加一个类的元素,当你超过 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. }

特殊点

不要让值和选择器难以覆盖。减少使用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. }

override

override 的样式让选择器和调试困难。尽可能的避免它。

  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. }

继承

不要重复声明样式,是可以继承的。

  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. }

简洁

保持代码简洁。尽可能的使用简写属性,避免使用多个属性。

  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. }

语言编码

只能是英语和数字

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

前缀

积极除掉过时的前缀。如果你需要使用它们,插入他们的标准属性之前

  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. }

动画

用 transitions 代替 animations。动画执行的时候尽量避免使用其他属性,除了 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. }

单位

这个具体看场景,当你使用相对单位的时候推荐使用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. }

颜色

如果你需要使用透明,使用 rgba。否则,使用 16 进制格式的

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

图片

如果能用 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. }

Hacks

不要使用这些

  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

性能

代码的可读性,正确性,可表达性优于性能。JavaScript 基本上不会有性能上的瓶颈。需要优化的东西像 图片优化,网络请求优化,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);

无状态

尽量让你的函数保持干净,所有的函数最好没有副作用,不要使用外部数据,返回一个新的对象代替现在已经存在的。

  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" }

原生方法

尽可能的使用语言自带的方法

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

类型转换(隐式转换)

请放心使用类型隐式转换当那样做有意义的时候,虽然说是要避免使用它,但是也不要盲目相信权威。

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

循环

当你不得已使用可变的对象时最好不要使用循环,使用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);

这是一个通用的循环函数),让递归更简单

Arguments

忘了 arguments 对象。其他的参数是个更好的选择,因为:

  1. 可以命名,能够让你有个更符合函数期待的参数
  2. 和数组没啥大区别,可以让你更方便的使用
  1. // bad
  2. const sortNumbers = () =>
  3. Array.prototype.slice.call(arguments).sort();
  4. // good
  5. const sortNumbers = (...numbers) => numbers.sort();

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()

  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. }

高阶函数

当你没必要的时候避免使用嵌套函数

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

组合

避免多个函数的嵌套,使用组合代替

  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

缓存

  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

变量

建议使用 const 代替 let,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");

条件

建议用 匿名执行函数返回语句 代替 if,else,switch 语句。

  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. })();

对象迭代

尽可能的避免使用 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 创建对象

在使用对象的时候,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

柯里化

柯里化很强大,但是很多开发者不是很熟悉。不要滥用它,但适当的使用是很不错的。

  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

可读性

不要用一些看似聪明的小技巧混淆代码的可读性

  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);

代码复用

不要害怕创造许多小的,高度组合可重复使用的函数

  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);

依赖

减少依赖,你不熟悉第三方代码,不要为了一个简单的方法加载一个库。

  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 => [...Set(arr)];
  9. const union = (...arr) => unique([].concat(...arr));
  10. compact(["foo", 0]);
  11. unique(["foo", "foo"]);
  12. union(["foo"], ["bar"], ["foo"]);