使用Lighthouse进行网页性能测试
-
简介
Lighthouse可用于测试网页性能,以及给出具体的优化建议。lighthouse使用起来也特别方便,下面一起来了解下吧。
安装
使用lighthouse有两种方式:
-
Chrome自带lighthouse功能
打开开发者工具即可看到 -
命令行
# 安装 npm install lighthouse # 运行 lighthouse https://google.com # 配置选项 lighthouse https://google.com --only-categories=performance --output html --output-path ./report.html
- 实践
这里直接使用Chrome开发者工具中的lighthouse对某网页进行了测试,以下是测试的总评分结果:
评分分为几项:Performance、Accessibility、Best Paractices、SEO、Progressive Web App。关于这五个大的方面,每一项 lighthouse都会给出更具体的评分和优化建议。
下面列举一下这次测试中对于Performance给出的具体建议:
-
Does not use passive listeners to improve scrolling performance
-
Serve static assets with an efficient cache policy
-
Avoid an excessive DOM size
A large DOM will increase memory usage, cause longer style calculations, and produce costly layout reflows. Learn more
-
Defer offscreen images
-
Minify CSS and JavaScript
-
Preconnect to required origins
Consider adding
preconnect
ordns-prefetch
resource hints to establish early connections to important third-party origins- Avoid multiple page redirects
Redirects introduce additional delays before the page can be loaded
- Preload key requests
Consider using
<link rel=preload>
to prioritize fetching resources that are currently requested later in page load- Use video formats for animated content
Large GIFs are inefficient for delivering animated content. Consider using MPEG4/WebM videos for animations and PNG/WebP for static images instead of GIF to save network bytes. Learn more
- Uses HTTP/2 for its own resources
HTTP/2 offers many benefits over HTTP/1.1, including binary headers, multiplexing, and server push. Learn more.
总结起来有两个方面:
-
网络方面
-
延迟加载没有用到的CSS和Javascript资源,以及图片资源。
-
文本(CSS、)压缩、使用更优化的图片格式,比如webp,以及替换大的GIF图。减小网络负载。
-
静态文件使用合适的缓存策略。
-
Preconnect to required origins / Preload key requests
preconnect
ordns-prefetch
/<link rel=preload>
-
使用HTTP/2
优点:二进制头,多路复用。
-
避免大量的页面的重定向
-
-
代码方面
-
监听滚动事件时尽量使用
passive:true
相当于告知浏览器此滚动监听事件不会阻止滚动
-
避免大量的DOM渲染
会增加内存占用,同时有很大的重排重绘开销
-
CSS减少嵌套
-
通过这些建议我们就能对网站进行有针对性的改进了~
另外,如果想了解lighthouse的实现原理,可以参考 Lighthouse 测试内幕
-