# 前端性能优化

# 页面渲染(js单线程,原因避免dom渲染冲突)

  1. DOCTYPE作用
    • HTML5 <!DOCTYPE html>
    • HTML4.01 Strict(严格模式),不包含弃用的元素(font标签)
    • HTML4.01Transitional(传统模式)包含弃用的元素(font标签)
  2. 浏览器渲染过程
  3. 重绘重排

# dom操作

  1. 缓存daom
  2. 暂存dom
  3. 事件节流
  4. 尽早操作 load DOMContentLoaded

# 页面性能

  1. 资源合并压缩

  2. 非核心代码异步加载

    1. 动态脚本加载
    2. defer,在html解析完成后才会执行,如果是多个安装顺序依次执行
    3. async,加载完成后立即执行,如果是多个,执行顺序与加载顺序无关
  3. 利用浏览器缓存

    1. 强缓存

      • expires Http1.0 中的标准,表明过期时间,注意此处的时间都是指的是服务器的时间。可以看到过期时间被设定为了:Thu, 28 Sep 2017 06:38:37 GMT存在的问题:服务器时间与客户端时间的不一致,就会导致缓存跟期待效果出现偏差。
      • Cache-Control Http1.1 中的标准,可以看成是 expires 的补充。使用的是相对时间的概念。简单介绍下Cache-Control的属性设置。
      • max-age: 设置缓存的最大的有效时间,单位为秒(s)。max-age会覆盖掉Expires
    2. 协商缓存

      在这个阶段,服务器一般会将Cache-controlexpireslast-modifieddateetag (hash值)等字段在response header 中返回,便于下次缓存。当然具体的场景,也是看服务器的约定规则设定。

  4. 使用CDN

  5. cdn预解析

<meta http-equiv="x-dns-prefetch-control" content="on" />   //页面中的a标签一般会自动预解析,若是https协议,默认关闭dns预解析,这里强制预解析
<link rel="dns-prefetch" href="http://bdimg.share.baidu.com" />
1
2

# 错误监控

js中共有6种错误类型

  1. SyntaxError 语法错误

  2. ReferenceError 引用错误

  3. TypeError 类型错误

  4. RangeError 范围错误 参数超范围

  5. EvalError

  6. URIError

  7. 错误分类

    • 及时运行错误:代码错误

      try...catch window.onerror

    • 资源加载错误(不会冒泡)

      1. object.onerror
      2. performance.getEntries() (获得页面所有加载的资源,根据已经加载的资源间接判断加载失败的资源)
      3. Error事件捕获
      <script type="text/javascript">
          window.addEventListener('error', function (e) {
              console.log('捕获', e);
          }, true);//这里一定是true表示要捕获
      </script>
      
      1
      2
      3
      4
      5
    • 跨域的js能捕获到错误

      • 错误信息:script:error
      • 出错行号和出错列拿不到为0
      • 解决:
        1. 第一步,在客户端script增加crossorign属性
        2. 第二步,在服务端设置js响应头Access-Control-Allow-Orign:*(或者指定域名)
  8. 上报错误

    1. 利用ajax通信进行上报

    2. 利用image对象上报(大多数都用这个,简单,不用借助其他的库,一行代码解决所有)

      eg:(new Image()).src = 'http://baidu.com/tesjk?r=tksjk';

# performance.timing:利用performance.timing进行性能分析

window.onload = function(){
    setTimeout(function(){
        let t = performance.timing
        console.log('DNS查询耗时 :' + (t.domainLookupEnd - t.domainLookupStart).toFixed(0))
        console.log('TCP链接耗时 :' + (t.connectEnd - t.connectStart).toFixed(0))
        console.log('request请求耗时 :' + (t.responseEnd - t.responseStart).toFixed(0))
        console.log('解析dom树耗时 :' + (t.domComplete - t.domInteractive).toFixed(0))
        console.log('白屏时间 :' + (t.responseStart - t.navigationStart).toFixed(0))
        console.log('domready时间 :' + (t.domContentLoadedEventEnd - t.navigationStart).toFixed(0))
        console.log('onload时间 :' + (t.loadEventEnd - t.navigationStart).toFixed(0))

        if(t = performance.memory){
            console.log('js内存使用占比 :' + (t.usedJSHeapSize / t.totalJSHeapSize * 100).toFixed(2) + '%')
        }
    })
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 摘自

# 今日图 性能的重要性

ewewwe.gif