如何衡量前端性能:一个案例性研究

137 阅读2分钟

有时候,说服客户关注下前端性能,以便在开发中获取更充裕的时间来做优化,时间很难的事情,毕竟有时你很难讲清楚做了优化和不做优化的差异在哪里,所以毫不夸张的说,如果性能量化做得好,那么性能工作就已经完成了一大半。

以前给客户增加新特性的时候,往往要花费数周的时间才能获取到效果提升的数据,周期实在太长,让我们的收益风险变得太大

我们的需求是,想要找到一种方式,来聚焦在每个客户在页面head标签内的性能,而且不要谈“我认为”,而是要拿出实实在在的数据,以可量化的直观数据来让用户认识到性能的提升。

获取性能数据

首先可以做的事情就是建立一个快照,这样我们就能轻松的比对出性能优化前后的差异。Chrome浏览器的开发者工具性能tab提供了很多实用的信息,但是像下面这样的一张图对于不熟悉的人来说理解起来实在是困难。

image.png

因此,我们决定抛开Chrome DevTools的Performance,而是采用浏览器的Performance API 来获取到底层的性能信息。

我们需要利用Chrome的Overrides功能,以便于对目标网页注入一些JavaScript代码段

image.png

在这里,我们使用两个简单的函数:performance.mark(),performance.measure(),其用法也十分简单

// Start your measure
performance.mark('begin');
// Put everything you want to measure between the marks
// Stop your measure
performance.mark('end');
// Calculate the time difference between your 2 marks
performance.measure('diff', 'begin', 'end');
// View the results in the Performance tab
// or output the results in the console using:
console.log(performance.getEntriesByType("measure"));

当我们运行performance.getEntriesByType("measure")的时候,会得到一个类似的结果,可以知道耗时信息

image.png

更为重要的是,我们可以在Chrome DevTools的Performance的Timings看到具体的数据

image.png

此处<head><body>即为自定义的measure,我们看到Chrome已经对performance.measure做了整合。

结论

我们可以通过performance.markperformance.measure来获取到性能数据来衡量,并以此为依据来记录性能优化的程度了。