How to do front-end performance optimization (Part 1)

Work together to create and grow together! This is the 7th day of my participation in the "Nuggets Daily New Plan · August Update Challenge", click to view the details of the event .

foreword

Front-end performance optimization is another high-sounding word 118B6482.gif, indeed, because it is needed 高在性能,大在范围. Fortunately, many big guys have already output a lot of high-quality content for your reference. The author is also learning and understanding this content recently. If there is any inappropriate understanding of some of the following, you can correct it in the comment area! ! !

The content of front-end performance optimization is planned to be divided into two parts . I originally planned to finish one part, but I found that the pre-knowledge part has already taken up the 3000+text . Therefore, this article mainly explains some pre-requisites that need to be understood.

What exactly is front-end performance optimization optimizing?

In fact, the core of front-end performance optimization is two points:

  • Guaranteed faster loading of resources : the faster the rendering, the faster the view is displayed
  • Guarantee faster rendering speed/interaction speed of the view : the user interacts with the page, the premise is that the page needs to be rendered, and the second is that the page needs to be fed back as soon as possible, the purpose is to ensure a good user experience

And these core contents can be extended from the following common question.

What happens from input URLto page load completion?

I believe that up to now, everyone's answer to this question can be said to be able to eloquently (如果不能,请忽略)! However, the direction and focus of each answer should be different. For example B 站, winterthe perspective and analysis of the big guy in listening to this issue is deeper and wider.

Here is a brief summary of the core content:

  • to DNSparse
  • establish TCPconnection
  • Client sends HTTPrequest
  • server response HTTPresource
  • 浏览器获取响应内容,进行解析和渲染

以上任意一点都可进行无限扩展、延伸,但点到为止才是现在真正需要的。

性能指标

RAIL 模型

Google 为前端页面性能的评估提出了 RAIL 模型,核心内容如下:

  • Response 响应
  • Animation 动画
  • Idle 空闲
  • Load 加载

常规性能指标

性能指标其实有不少的内容,但在这我们指列举比较常用的几种:

  • 首次绘制(First Paint,FP
    • 在渲染进程确认要渲染当前响应资源后,渲染进程会先创建一个空白页面,通常把创建空白页面的这个时间点称为 First Paint,简称 FP
    • 所谓的 白屏时间 其实指的就是创建这个空白页面到浏览器开始渲染非空白内容的时间,比如页面背景发生变化等
  • 首次内容绘制(First Contentful Paint,FCP
    • 当用户看见一些 "内容" 元素被绘制在页面上的时间点,和白屏是不一样,它可以是 文本 首次绘制,或 SVG 首次出现,或 Canvas 首次绘制等,即当页面中绘制了第一个 像素 时,这个时间点称为 First Content Paint,简称 FCP
  • 首屏时间 / 最大内容绘制(Largest Contentful Paint, LCP
    • LCP 是一种新的性能度量标准,LCP 侧重于用户体验的性能度量标准,与现有度量标准相比,更容易理解与推理,当首屏内容完全绘制完成时,这个时间点称为 Largest Content Paint,简称 LCP
    • 最大内容绘制应在 2.5s 内完成
  • 首次输入延迟(First Input Delay, FID
    • FID 测量的是当用户第一次在页面上交互的时候(点击链接点击按钮自定义基于 js 的事件),到浏览器实际开始处理这个事件的时间
    • 首次输入延迟应在 100ms 内完成
  • 累积布局偏移(Cumulative Layout Shift, CLS)
    • CLS 是为了测量 视觉稳定性,以便提供良好的用户体验
    • 累积布局偏移应保持在 0.1 或更少
  • 首字节达到时间(Time to First Byte,TTFB
    • 指的是浏览器开始收到服务器响应数据的时间(后台处理时间 + 重定向时间),是反映服务端响应速度的重要指标
    • TTFB 时间如果超过 500ms,用户在打开网页的时就会感觉到明显的等待

性能指标工具

通过上述内容了解了性能指标的相关内容和一些阀值,那么接下来的问题是我们怎么获取一个网站的具体性能指标数据呢?

为了方便还是得使用工具或者说是 API,当然可以 自定义页面性能指标 的计算方式,比如有些就是通过计算当前页面 DOM总节点数嵌套层级 来计算一个网站的分数等,这里就不再额外介绍。

Performance 面板(Google)

具体参数介绍可以看 Big shark@LX 大佬的文章,里面介绍的非常详细,这里只列举一些核心点。

火焰图

Networks 指标

通过 Networks 指标可以查看到对应服务器加载资源的相关信息:

可以将鼠标 移动点击 到具体的请求上查看加载时间和加载速度,如下:

鼠标移入:

鼠标点击:

Frames 指标

通过 Frames 指标可以查看页面每一帧渲染时 CPU 所消耗的时间和持续时间 Duration 的信息,如下:

图一:

图二:

Timings 指标

通过 Timings 指标可以查看在上面列举的一些性能指标的值,如下:

  • 首次绘制(First Paint,FP
  • 首次内容绘制(First Contentful Paint,FCP
  • 首屏时间 / 最大内容绘制(Largest Contentful Paint, LCP
  • HTML 文档被完全加载 和 解析完成的时间(DOMContentLoaded, DCL

Main 指标

Main 指标包含了加载过程的三个阶段:

  • 导航阶段
    • 主要是处理响应头的数据,并执行一些老页面退出之前的清理操作
  • 解析 HTML 文件阶段
    • 主要是解析 HTML 数据、解析 CSS 数据、执行 JavaScript 来生成 DOMCSSOM
  • 生成位图阶段
    • 主要是将生成的 DOMCSSOM 合并,包括了布局 (Layout)、分层、绘制、合成等一系列操作

Lighthouse 面板(Google)

Performance 面板最大的优点就是各种数据信息非常的全,但这也是它最大的缺点,数据信息庞大到需要自行过滤,对于不熟悉的开发者来说,还是需要一定的学习成本的。

相反,Lighthouse 面板中的信息就相对简洁一些,除了检测结果以外,还会提供对应的改进方案,真是考虑得妥妥的,主要检测五个方面的内容:

  • Performance(性能)
  • Accessibility(可访问性)
  • Best practice(最佳实践)
  • SEO(搜索引擎优化)
  • Progressive Web App(渐进式 Web 应用)

可以通过 Analyze page load 按钮来开始对页面应用进行检测,这里以掘金首页为例:

下面以 Performance 性能 为例简单看一下具体包含的内容,由于篇幅有限,其他内容可自行测试并进行阅读。

Performance 性能(举一反三)

从性能指标的数据来看,只有 累积布局偏移(Cumulative Layout Shift, CLS) 满足要求,其他指标显示 黄色红色,意味着仍有改进的空间,特别是 首屏时间2.9s 已经是超过了对应的阈值 2.5s

性能指标数据如下图所示:

甚至还提供了对应的诊断结果,比如提到的图片没有设置对应的宽高:

Using the Node CLI

甚至还支持在 Node 环境运行,感兴趣的自行去 npm 中查看 文档 即可,这里不过多介绍。

性能指标数据收集

上述性能指标工具的能力已经足够强大,覆盖信息也很全面,但如果我们需要将页面性能指标数据收集并上报又该怎么办呢?

首先排除的肯定是通过 性能指标工具 的方式来收集,一旦要检测性能指标数据意味着得是不同的客户端统计数据的结果合集(除非你愿意一台一台客户端来手动记录和收集数据,呸,你愿意你领导还不愿意呢),最理想的方式当然是自动收集和上报,那就意味着这应该是代码要干的活!!!

既然有这样的需求,那么必定有对应的解决方案,您接着往下看!

Performance API

实际上在浏览器端的全局对象 window 上有一个名为 performance 的属性,它是一个用于支持 IE9 以上及 webkit 内核浏览器中用于记录页面 加载解析 过程中关键时间点的机制,其兼容性在 caniuse 中的表现如下:

下面就简单介绍一下和 window.performance 相关一些核心属性和方法。

performance.timing 属性

performance.timing 属性中提供了很多关键的时间信息,我们可以通过这些时间节点来简单的计算出需要的性能指标数据(不一定准确),计算方式如:

const {
 domainLookupStart,
 domainLookupEnd,
 navigationStart,
 loadEventEnd,
 responseStart,
 responseEnd,
 connectStart,
 connectEnd,
 redirectStart,
 redirectEnd,
 domContentLoadedEventEnd,
 domComplete,
} = performance.timing

// DNS 查询时间
DNS = domainLookupEnd - domainLookupStart

// TCP 建立连接时间
TCP = connectEnd - connectStart

// 页面重定向时间
Redirect = redirectEnd - redirectStart

// 首字节到底时间
TTFB = responseStart - navigationStart

// 首次渲染时间
FP = responseStart - navigationStart

// DOM 解析时间
DOM = domComplete - responseEnd

// 首屏时间
LCP = loadEventEnd - navigationStart
复制代码

performance.getEntries() 方法

performance.getEntries() 方法可以获取所有资源请求的时间数据,如下:

点击可查看具体的资源信息,其他属性和上述内容有重复,就不在额外介绍计算方式了,具体如下:

performance.now() 方法

performance.now() 方法可以精确计算程序执行时间,它会返回以微秒(百万分之一秒)为单位的时间,即更加精准,这也是它和 Date.now() 是不同点:

  • Date.now() 返回自 1970年1月1日 00:00:00 (UTC) 到 当前时间毫秒数

    • Means Date.now()depend on the current time of the system, and the system time can be considered modified, so it's not accurate in milliseconds
  • performance.now()The time is incremented at a constant rate and is not affected by the system time

    // Date.now()
    let a = 2, b = 3;
    const begin = Date.now();
    console.log(' a + b = ', a + b);
    
    console.log('time = ', Date.now() - begin); // 2
    
    // performance.now()
    let a = 2, b = 3;
    const begin = performance.now();
    console.log(' a + b = ', a + b);
    
    console.log('time = ', performance.now() - begin); // 0.10000002384185791
    复制代码

Web Vitals

web-vitalsThe library Googleis a small (approximately 1.5K) modular library launched by the company to measure all Web Vitalsrelevant . Its important core indicator information is as follows (a picture is worth a thousand words):

Next, let npx create-react-app my-react-app's create a reactproject with and take a look at its project structure:

image.png

Is it super conspicuous? reportWebVitals.jsAfter entering the file, you will find that the core performance indicators we need are all in it:

at last

The content of front-end performance optimization has been planned to be written before. After all, there is a lack of knowledge. So far, it can be regarded as outputting while learning. The next article will summarize some performance optimization solutions! ! !

1810425E.jpg

If the above content is helpful to you, come to one-click three-link, need the power of light! ! !

1811882C.gif

Guess you like

Origin juejin.im/post/7137058832592666655