# 整体思路
因为性能优化是一个很复杂和庞大的工作,两种场景:1. 专门优化某个细节,那用对应的策略即可;2. 对整个项目实施优化,那就得有个整体思路。
关键渲染路径(CRP):url ——> DNS解析获得IP ——> TCP三次握手建立连接 ——> http请求/响应 ——> 解析渲染
DSN解析获得IP:DNS预解析,在head区域,将项目会用到的域名,通过dns-prefetch
进行预解析。
<link ref="dbs-prefetch" href="//search.baidu.com"/>
<link ref="dbs-prefetch" href="//map.baidu.com"/>
TCP三次握手建立连接:http1.0每次请求都建立连接会很浪费时间,而http1.1引入了长连接概念(keep-alive:true 默认开启),可以在一次tcp连接中发送多个http请求。
http请求/响应:减少请求数(资源合并)、减小请求数据大小(代码压缩、图片压缩、http1.1的range特性)、缓存(http缓存、浏览器缓存)
解析渲染:
js性能量化API:performance,其中属性 timing 表示从输入 url 到可以使用页面的全过程时间统计,返回一个 PerformanceTiming 对象,单位均为毫秒。
常用计算:
- DNS查询耗时 :domainLookupEnd - domainLookupStart
- TCP链接耗时 :connectEnd - connectStart
- request请求耗时 :responseEnd - responseStart
- 解析dom树耗时 : domComplete - domInteractive
- 白屏时间 :responseStart - navigationStart
- domready时间(用户可操作时间节点) :domContentLoadedEventEnd - navigationStart
- onload时间(总下载时间) :loadEventEnd - navigationStart
性能评估工具:lighthouse
图片优化:从图片的压缩算法角度
- 从模糊到清晰,小波算法,得到渐进式图片
- 从上到下逐渐显示,离散余弦算法,得到标准型图片