前端性能优化

前端性能优化的宗旨即追求更快,但是也应避免过渡优化。以现有互联网产品为例各厂商性能标准也不一致,在各标准找到适合自己公司用户体量及业务要求的标准需要不断的实践。

前端性能指标

  • TTFB : ResponseStart - RequestStart (首包时间,关注网络链路耗时)
  • FPT : ResponseEnd - FetchStart (首次渲染时间 / 白屏时间)
  • TTI : DomInteractive - FetchStart (首次可交付时间)
  • Ready : DomContentLoadEventEnd - FetchStart (加载完成时间)
  • Load : LoadEventStart - FetchStart (页面完全加载时间)

performance timing api

  • 计算常见指标可以使用谷歌封装好的js库web-vitals
    performance timing api

FMP(first meaningful paint)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
const utils = {
//获取当前样式
getStyle(element, att) {
//特性侦测
if (window.getComputedStyle) {
//优先使用W3C规范
return window.getComputedStyle(element)[att];
} else {
//针对IE9以下兼容
return element.currentStyle[att];
}
}
}

const START_TIME = performance && performance.timing.responseEnd;
const IGNORE_TAG_SET = ["SCRIPT", "STYLE", "META", "HEAD", "LINK"];
const TAG_WEIGHT_MAP = {
SVG: 2,
IMG: 2,
CANVAS: 4,
OBJECT: 4,
EMBED: 4,
VIDEO: 4
};
const LIMIT = 1000;
const WW = window.innerWidth;
const WH = window.innerHeight;
const VIEWPORT_AREA = WW * WH;
const DELAY = 500;
class FMPTiming {
constructor() {
this.statusCollector = [];
this.flag = true;
this.muo = MutationObserver;
this.observer = null;
this.callbackCount = 1;
this.mp = {};
this.initObserver();
}
firstSnapshot() {
let t = window.__DOMSTART - START_TIME;
let bodyTarget = document.body;
if (bodyTarget) {
this.doTag(bodyTarget, this.callbackCount++);
}
this.statusCollector.push({
t
});
}
initObserver() {
this.firstSnapshot();
this.observer = new MutationObserver(() => {
let t = Date.now() - START_TIME;
let bodyTarget = document.body;
if (bodyTarget) {
this.doTag(bodyTarget, this.callbackCount++);
}
this.statusCollector.push({
t
});
});
this.observer.observe(document, {
childList: true,
subtree: true
});
if (document.readyState === "complete") {
this.calFinallScore();
} else {
window.addEventListener(
"load",
() => {
this.calFinallScore();
},
true
);
}
}

initResourceMap() {
performance.getEntries().forEach(item => {
this.mp[item.name] = item.responseEnd;
});
}

doTag(target, callbackCount) {
let tagName = target.tagName;
if (IGNORE_TAG_SET.indexOf(tagName) === -1) {
let childrenLen = target.children ? target.children.length : 0;
if (childrenLen > 0) {
for (let childs = target.children, i = childrenLen - 1; i >= 0; i--) {
if (childs[i].getAttribute("f_c") === null) {
childs[i].setAttribute("f_c", callbackCount);
}
this.doTag(childs[i], callbackCount);
}
}
}
}

calFinallScore() {
if (MutationObserver && this.flag) {
if (!this.checkCanCal(START_TIME)) {
console.time("calTime");
this.observer.disconnect();
this.flag = false;
let res = this.deepTraversal(document.body);
let tp;
res.dpss.forEach(item => {
if (tp && tp.st) {
if (tp.st < item.st) {
tp = item;
}
} else {
tp = item;
}
});
console.log(tp, this.statusCollector);
this.initResourceMap();
let resultSet = this.filterTheResultSet(tp.els);
let fmpTiming = this.calResult(resultSet);
console.log("fmp : ", fmpTiming);
console.timeEnd("calTime");
} else {
setTimeout(() => {
this.calFinallScore();
}, DELAY);
}
}
}

calResult(resultSet) {
let rt = 0;
resultSet.forEach(item => {
let t = 0;
if (item.weight === 1) {
let index = +item.node.getAttribute("f_c") - 1;
t = this.statusCollector[index].t;
} else if (item.weight === 2) {
if (item.node.tagName === "IMG") {
t = this.mp[item.node.src];
} else if (item.node.tagName === "SVG") {
let index = +item.node.getAttribute("f_c") - 1;
t = this.statusCollector[index].t;
} else {
//background image
let match = utils.getStyle(item.node, 'background-image').match(/url\(\"(.*?)\"\)/);

let s;
if (match && match[1]) {
s = match[1];
}
if (s.indexOf("http") == -1) {
s = location.protocol + match[1];
}
t = this.mp[s];
}
} else if (item.weight === 4) {
if (item.node.tagName === "CANVAS") {
let index = +item.node.getAttribute("f_c") - 1;
t = this.statusCollector[index].t;
} else if (item.node.tagName === "VIDEO") {
t = this.mp[item.node.src];

!t && (t = this.mp[item.node.poster]);
}
}
console.log(t, item.node);
rt < t && (rt = t);
});
return rt;
}

filterTheResultSet(els) {
let sum = 0;
els.forEach(item => {
sum += item.st;
});
let avg = sum / els.length;
return els.filter(item => {
return item.st > avg;
});
}

deepTraversal(node) {
if (node) {
let dpss = [];
for (let i = 0, child; (child = node.children[i]); i++) {
let s = this.deepTraversal(child);
if (s.st) {
dpss.push(s);
}
}
return this.calScore(node, dpss);
}
return {};
}

calScore(node, dpss) {
let {
width,
height,
left,
top,
bottom,
right
} = node.getBoundingClientRect();
let f = 1;
if (WH < top || WW < left) {
//不在可视viewport中
f = 0;
}
let sdp = 0;
dpss.forEach(item => {
sdp += item.st;
});
let weight = TAG_WEIGHT_MAP[node.tagName] || 1;
if (
weight === 1 &&
utils.getStyle(node, 'background-image') &&
utils.getStyle(node, 'background-image') !== "initial"
) {
weight = TAG_WEIGHT_MAP["IMG"]; //将有图片背景的普通元素 权重设置为img
}
let st = width * height * weight * f;
let els = [{ node, st, weight }];
let areaPercent = this.calAreaPercent(node);
if (sdp > st * areaPercent || areaPercent === 0) {
st = sdp;
els = [];
dpss.forEach(item => {
els = els.concat(item.els);
});
}
return {
dpss,
st,
els
};
}

checkCanCal(start) {
let ti = Date.now() - start;
return !(
ti > LIMIT ||
ti -
((this.statusCollector &&
this.statusCollector.length &&
this.statusCollector[this.statusCollector.length - 1].t) ||
0) >
1000
);
}

calAreaPercent(node) {
let {
left,
right,
top,
bottom,
width,
height
} = node.getBoundingClientRect();
let wl = 0;
let wt = 0;
let wr = WW;
let wb = WH;
let overlapX =
right - left + (wr - wl) - (Math.max(right, wr) - Math.min(left, wl));
if (overlapX <= 0) {
//x 轴无交点
return 0;
}
let overlapY =
bottom - top + (wb - wt) - (Math.max(bottom, wb) - Math.min(top, wt));
if (overlapY <= 0) {
return 0;
}
return (overlapX * overlapY) / (width * height);
}
}

new FMPTiming();

FCP(first contentful paint)

  • 含义:浏览器第一次绘制非背景内容时间(文本、图片、非白色canvas或svg)
  • 统计逻辑:通过performance.getEntriesByType(‘paint’),取第二个pain的时间,或者通过Mutation Observer观察到首次节点变动的时间。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const domEntries = []
const observer = new MutationObserver((mutationsList)=>{
for(var mutation of mutationsList) {
if (mutation.type == 'childList') {
console.log('A child node has been added or removed.')
}
if (mutation.type == 'addedNodes') {
//TODO新增了节点,做处理,计算此时的可见性/位置/出现时间等信息,然后 push 进数组
domEntries.push(mutation)
}
}
})

function getFPTime(){
const timings = performance.getEntriesByType('paint');
if(timings.length > 1)return timings[1]
return timings ? Math.round(timings.startTime) : null
//伪代码,算 DOM 变化时的最小那个时间,即节点首次变动的时间
return Math.round(domEntries.length ? Math.min(...domEntries.map(entry => entry.time)) : 0)
}

前端性能分析工具

lightHouse
WebPageTest