Skip to content

前端性能优化 #188

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
CongratulateWE opened this issue Oct 9, 2022 · 0 comments
Open

前端性能优化 #188

CongratulateWE opened this issue Oct 9, 2022 · 0 comments
Labels

Comments

@CongratulateWE
Copy link
Owner

CongratulateWE commented Oct 9, 2022

一道高频的面试题目:

从输入 URL 到页面加载完成,发生了什么?

我们将这个过程切分为如下的过程片段:

DNS 解析
TCP 连接
HTTP 请求抛出
服务端处理请求,HTTP 响应返回
浏览器拿到响应数据,解析响应内容,把解析的结果展示给用户

我们以以上五个步骤为主线,探讨应该如何进行前端性能的优化。

image

Webpack 优化建议

#183 (comment)

图片优化

JPEG/JPG
关键字:有损压缩、体积小、加载快、不支持透明

PNG-8 与 PNG-24
关键字:无损压缩、质量高、体积大、支持透明

SVG
关键字:文本文件、体积小、不失真、兼容性好

Base64
关键字:文本文件、依赖编码、小图标解决方案

浏览器缓存

Memory Cache
Service Worker Cache
HTTP Cache
Push Cache

HTTP 缓存是我们日常开发中最为熟悉的一种缓存机制。它又分为强缓存协商缓存。优先级较高的是强缓存,在命中强缓存失败的情况下,才会走协商缓存。

强缓存的实现:从 expires 到 cache-control。
expires 允许我们通过绝对的时间戳来控制缓存过期时间,相应地,Cache-Control 中的max-age 字段也允许我们通过设定相对的时间长度来达到同样的目的。
Cache-Control 的 max-age 配置项相对于 expires 的优先级更高。当 Cache-Control 与 expires 同时出现时,我们以 Cache-Control 为准。

cache-control 头的 no-cache 和 no-store
no-cache 绕开了浏览器:我们为资源设置了 no-cache 后,每一次发起请求都不会再去询问浏览器的缓存情况,而是直接向服务端去确认该资源是否过期(即走我们下文即将讲解的协商缓存的路线)。

no-store 比较绝情,顾名思义就是不使用任何缓存策略。在 no-cache 的基础上,它连服务端的缓存确认也绕开了,只允许你直接向服务端发送请求、并下载完整的响应。

协商缓存的实现:从 Last-Modified 到 Etag

Etag 在感知文件变化上比 Last-Modified 更加准确,优先级也更高。当 Etag 和 Last-Modified 同时存在时,以 Etag 为准。

本地存储——从 Cookie 到 Web Storage、IndexedDB

参考:
https://juejin.cn/book/6844733750048210957
https://juejin.cn/post/6892994632968306702

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant