看到一份很受欢迎的前端代码指南,根据自己的理解进行了翻译,但能力有限,对一些JS代码理解不了,如有错误,望斧正。

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.  
  12. <!-- good -->
  13. <main>
  14. <article>
  15. <header>
  16. <h1>Blog post</h1>
  17. <p>Published: <time datetime="2015-02-21">21st Feb, 2015</time></p>
  18. </header>
  19. <p></p>
  20. </article>
  21. </main>

请确保正确使用语义化的标签,错误的用法甚至不如保守的用法。

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

简洁

确保代码简洁性,不要再采用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.  
  19. <!-- good -->
  20. <!doctype html>
  21. <html lang=en>
  22. <meta charset=utf-8>
  23. <title>Contact</title>
  24. <link rel=stylesheet href=style.css>
  25.  
  26. <h1>Contact me</h1>
  27. <label>
  28. Email address:
  29. <input type=email placeholder=you@email.com required>
  30. </label>
  31. <script src=main.js></script>
  32. </html>

可用性

可用性不应该是事后才考虑的事情。你不必成为WCAG专家来改进网站,你可以通过简单的修改做出不错的效果,例如;

  • 正确使用alt属性
  • 确保链接和按钮正确使用(不要用<div class="button">这种粗暴的做法)
  • 不依赖于颜色来传达信息
  • 给表单做好lable标记
  1. <!-- bad -->
  2. <h1><img alt="Logo" src="logo.png"></h1>
  3.  
  4. <!-- good -->
  5. <h1><img alt="My Company, Inc." src="logo.png"></h1>

语言

定义语言和字符编码是可选项,建议在文档级别处定义。使用UTF-8编码。

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

性能

除非有非要在加载内容前加载脚本的必要性由,不然别这样做,这样会阻碍网页渲染。如果你的样式表很大,必须独立放到一个文件里。两次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.  
  8. <!-- good -->
  9. <!doctype html>
  10. <meta charset=utf-8>
  11. <title>Hello, world.</title>
  12. <p>...</p>
  13. <script src=analytics.js></script>

CSS

分号

不能漏写分号

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

盒模型

整个文档的盒模型应该要相同,最好使用global * { box-sizing: border-box; }定义。不要修改某个元素的盒模型。

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

尽量不要改变元素默认行为。保持默认的文本流。比如,移出一个图片下面的一个白块,不影响原本的显示:

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

类似的,尽量不要改变浮动方式。

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

定位

有很多CSS定位方法,尽量避免使用以下方法,根据性能排序:

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

选择器

紧密耦合DOM选择器,三个层级以上建议加class:

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

避免不必要的写法:

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

指明

不要让代码难于重写,让选择器更精确,减少ID、避免使用!important

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

覆盖

覆盖样式会使维护和调试更困难,所以要尽量避免。

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

继承

不要把可继承的样式重复声明:

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

简洁

保持代码的简洁。使用属性缩写。不必要的值不用写。

  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.  
  12. /* good */
  13. div {
  14. transition: 1s;
  15. top: calc(50% - 10px);
  16. padding: 5px 10px 20px;
  17. }

语言

能用英文的时候不用数字。

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

供应商的前缀

砍掉过时的供应商前缀。必须使用时,需要放在标准属性前:

  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.  
  13. /* good */
  14. div {
  15. -webkit-transform: scale(2);
  16. transform: scale(2);
  17. transition: 1s;
  18. }

动画

除了变形和改变透明度用animation,其他尽量使用transition

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

单位

可以不用单位时就不用。建议用rem。时间单位用sms好。

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

颜色

需要做透明效果是用rgba,否则都用16进制表示:

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

绘图

减少HTTPS请求,尽量用CSS绘图替代图片:

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

注释

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

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.  
  12. // good
  13. const arr = [1, 2, 3, 4];
  14. const isEven = n => n % 2 == 0;
  15. const square = n => n * n;
  16.  
  17. 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.  
  5. // good
  6. const merge = (...sources) => Object.assign({}, ...sources);
  7. merge({ foo: "foo" }, { bar: "bar" }); // => { foo: "foo", bar: "bar" }

尽量使用内置方法

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

严格条件

在非必要严格条件的情况不要使用。

  1. // bad
  2. if (x === undefined || x === null) { ... }
  3.  
  4. // good
  5. 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.  
  11. sum([1, 2, 3]); // => 6
  12.  
  13. // good
  14. const sum = arr =>
  15. arr.reduce((x, y) => x + y);
  16.  
  17. sum([1, 2, 3]); // => 6
  18. If you can't, or if using array.prototype methods is arguably abusive, use recursion.
  19.  
  20. // bad
  21. const createDivs = howMany => {
  22. while (howMany--) {
  23. document.body.insertAdjacentHTML("beforeend", "<div></div>");
  24. }
  25. };
  26. createDivs(5);
  27.  
  28. // bad
  29. const createDivs = howMany =>
  30. [...Array(howMany)].forEach(() =>
  31. document.body.insertAdjacentHTML("beforeend", "<div></div>")
  32. );
  33. createDivs(5);
  34.  
  35. // good
  36. const createDivs = howMany => {
  37. if (!howMany) return;
  38. document.body.insertAdjacentHTML("beforeend", "<div></div>");
  39. return createDivs(howMany - 1);
  40. };
  41. createDivs(5);

Arguments

忘记arguments对象吧,其他参数是更好的选择,因为:

  • 它已经被定义
  • 它是一个真的数组,很方便使用

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

Apply

忘记apply(),改用运算操作。

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

Bind

不用bind()方法,这有更好的选择:

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

更好的排序

避免多重嵌套:

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

Composition

避免方法嵌套调用,改用composition

  1. const plus1 = a => a + 1;
  2. const mult2 = a => a * 2;
  3.  
  4. // bad
  5. mult2(plus1(5)); // => 12
  6.  
  7. // good
  8. const pipeline = (...funcs) => val => funcs.reduce((a, b) => b(a), val);
  9. const addThenMult = pipeline(plus1, mult2);
  10. 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.  
  8. // good
  9. const contains = (() =>
  10. Array.prototype.includes
  11. ? (arr, value) => arr.includes(value)
  12. : (arr, value) => arr.some(el => el === value)
  13. )();
  14. contains(["foo", "bar"], "baz"); // => false

变量

const 优于 letlet 优于 var

  1. // bad
  2. var obj = {};
  3. obj["foo" + "bar"] = "baz";
  4.  
  5. // good
  6. const obj = {
  7. ["foo" + "bar"]: "baz"
  8. };

条件判断

用多个if,优于 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.  
  10. // good
  11. const grade = (() => {
  12. if (result < 50)
  13. return "bad";
  14. if (result < 90)
  15. return "good";
  16. return "excellent";
  17. })();

对象的操作

避免使用for...in

  1. const shared = { foo: "foo" };
  2. const obj = Object.create(shared, {
  3. bar: {
  4. value: "bar",
  5. enumerable: true
  6. }
  7. });
  8.  
  9. // bad
  10. for (var prop in obj) {
  11. if (obj.hasOwnProperty(prop))
  12. console.log(prop);
  13. }
  14.  
  15. // good
  16. 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.  
  12. // good
  13. const me = Map();
  14. me.set("name", "Ben");
  15. me.set("age", 30);
  16. me.size; // => 2
  17. me.set("country", "Belgium");
  18. me.size; // => 3

Curry

在别的语言里有Curry的一席之地,但在JS里避免使用。不然会是代码阅读困难。

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

可读性

不要使用自以为是的技巧:

  1. // bad
  2. foo || doSomething();
  3.  
  4. // good
  5. if (!foo) doSomething();
  6.  
  7. // bad
  8. void function() { /* IIFE */ }();
  9.  
  10. // good
  11. (function() { /* IIFE */ }());
  12.  
  13. // bad
  14. const n = ~~3.14;
  15.  
  16. // good
  17. const n = Math.floor(3.14);

代码重用

对写些小型、组件化、可重用的方法。

  1. // bad
  2. arr[arr.length - 1];
  3.  
  4. // good
  5. const first = arr => arr[0];
  6. const last = arr => first(arr.slice(-1));
  7. last(arr);
  8.  
  9. // bad
  10. const product = (a, b) => a * b;
  11. const triple = n => n * 3;
  12.  
  13. // good
  14. const product = (a, b) => a * b;
  15. 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.  
  7. // good
  8. const compact = arr => arr.filter(el => el);
  9. const unique = arr => [...Set(arr)];
  10. const union = (...arr) => unique([].concat(...arr));
  11.  
  12. compact(["foo", 0]);
  13. unique(["foo", "foo"]);
  14. union(["foo"], ["bar"], ["foo"]);

  


英文原文 Frontend Guidelines

GitHub 上一份很受欢迎的前端代码优化指南-强烈推荐收藏的更多相关文章

  1. GitHub 上一份很受欢迎的前端代码优化指南

    http://segmentfault.com/a/1190000002587334?utm_source=weekly&utm_medium=email&utm_campaign=e ...

  2. GitHub 上100个最受欢迎的Java基础类库

    作为一名整天与既成熟且不断发展的Java语言打交道的开发者,面对的困境之一就是在我们编写代码的时候,是使用一些人人谈论的人们新技术呢,还是坚持使用一些虽旧但成熟的类库? 由于Java应用中大部分是商业 ...

  3. Github上关于iOS的各种开源项目集合(强烈建议大家收藏,查看,总有一款你需要)

    下拉刷新 EGOTableViewPullRefresh - 最早的下拉刷新控件. SVPullToRefresh - 下拉刷新控件. MJRefresh - 仅需一行代码就可以为UITableVie ...

  4. GitHub上最火的、最值得前端学习的几个数据结构与算法项目!没有之一!

    Hello,大家好,我是你们的 前端章鱼猫. 简介 前端章鱼猫从 2016 年加入 GitHub,到现在的 2020 年,快整整 5 个年头了. 相信很多人都没有逛 GitHub 的习惯,因此总会有开 ...

  5. 给大家推荐:五个Python小项目,Github上的人气很高的

    1.深度学习框架 Pytorch https://github.com/pytorch/pytorch PyTorch 是一个 Torch7 团队开源的 Python 优先的深度学习框架,提供两个高级 ...

  6. github上所有项目的受欢迎程度排名,包括超大型项目

    直接打开如下网址: https://github.com/search?l=Java&q=+stars%3A%3E0&ref=searchresults&type=Reposi ...

  7. 2019年9月Github上最热门的JavaScript开源项目

      2019年9月Github上最热门的JavaScript开源项目 前端开发 前端开发 微信号 qianduan1024 功能介绍 专注于Web前端技术文章分享,包含JavaScript.HTML5 ...

  8. 在github上最热门好评高的ROS相关功能包

    在github上最热门最受欢迎的ROS相关功能包 下面依次列出,排名不分先后: 1  Simulation Tools In ROS https://github.com/ros-simulation ...

  9. 9 月份 GitHub 上最火的 JavaScript 开源项目!

    推荐 GitHub 上9 月份最受欢迎的 10 个 JavaScript 开源项目,在这些项目中,你有在用或用过哪些呢? 1.基于 Promise 的 HTTP 客户端 Axios https://g ...

随机推荐

  1. spring 整合 ActiveMQ

    1.1     JMS简介 JMS的全称是Java Message Service,即Java消息服务.它主要用于在生产者和消费者之间进行消息传递,生产者负责产生消息,而消费者负责接收消息.把它应用到 ...

  2. Java设计模式学习笔记(观察者模式)

    观察者模式说起来很简单,就是一个订报纸的模式.但是实际上这部分我觉得还是很有意思的,<Head First设计模式>里还有一些还没看完,也是因为理解的不够深吧. 观察者模式会包含两个组件: ...

  3. mongo 主从数据不同步

    在从库上执行如下命令: repset:SECONDARY> rs.slaveOk()repset:SECONDARY> db.runCommand({"resync": ...

  4. 解决"is marked as crashed and should be repaired"方法

    初次遇到这个问题是在服务器上放置mysql的磁盘空间满了(数据库目录和网站目录一定要做一定的分离,不要放在一个磁盘空间了) 当请求写入数据库时,php会提示 **** is marked as cra ...

  5. asp.net 导出Excel

    分享一个asp.net 导出假Excel代码.优点,不用借助于任何插件比如(NPOI),复制代码,修改grid.DataSource直接导出. 先看导出后的效果图 System.Web.UI.WebC ...

  6. 烂泥:学习ssh之ssh无密码登陆

    本文由秀依林枫提供友情赞助,首发于烂泥行天下 最近一个月没有写过文章,主要是刚刚换的新工作.新公司服务器OS使用的是ubuntu server版,和以前熟悉的centos还是有很多不同的. 刚好这几天 ...

  7. Sybase PowerDesign 导入数据库结构formSqlserver

    采用Sybase PD 创建数据库设计是常见的方法,如果遇到链接数据源时,无法直接链接系统数据源,而且在Sybase PD中无法直接创建odbc数据源时, 可以到控制面板中创建数据源,一步步的网络上有 ...

  8. android 读取根目录下的文件或文件夹

    @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setC ...

  9. webapp尺寸

    一.viewport宽度 起源:PC端的网站要显示在移动端有什么问题? 如果把移动端的可是区域设置到(320-768)的话,大部分网站都会因为太窄而显示错乱 所以浏览器默认把viewport[这个vi ...

  10. MVC、MVVM、MVP小结

    MVC MVC(Mode View Controller)是一种设计模式,它将应用划分为三个部分: 数据(模型).展现层(视图).用户交互(控制器). 一个事件发生的过程: ① 用户和应用产生交互 ② ...