一个站点的性能表现直接影响了用户体验,衡量站点的性能指标工具有很多,Google推出的Lighthouse即是这样的工具, Lighthouse详细指标参数可以参考相关文档。LIghthouse既可以作为浏览器插件使用,也可以使用命令参数进行跑分。
本文的场景需求是:每天自动多次跑分,并将性能指标数据上传,生成报表,供产研测及时关注性能情况,或可用来确认版本迭代结果分析依据之一。
基于场景需求,项目整体使用Linux+Lighthouse+eggjs(nodejs)技术选型,以下相关版本,仅供参考:
nodejs版本:v10.7.0
ChromeDriver版本:76.0.3809.68
Google Chrome版本:76.0.3809.100
Lighthouse版本:5.2.0
Linux下安装Google chrome
1.下载最新包
wget https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
2.安装查看
yum install ./google-chrome-stable_current_x86_64.rpm
// 查看是否安装成功
google-chrome --version
安装Google Chrome对应版本的ChromeDriver
可以在这http://chromedriver.storage.googleapis.com/index.html上面找对应版本的ChromeDriver,也是可以使用淘宝源https://npm.taobao.org/mirrors/chromedriver
// 下载
wget https://npm.taobao.org/mirrors/chromedriver/76.0.3809.68/chromedriver_linux64.zip
// 解压
unzip chromedriver_linux64.zip
// 移动到bin目录
move chromedriver /usr/bin/
// 查看是否安装成功
chromedriver --version
使用eggjs为服务端框架
关于eggjs详细请查阅egg官网,这里主要应用到了eggjs的定时任务模块https://eggjs.org/zh-cn/basics/schedule.html,根据自身需求设置好定时任务的执行间隔即可。
以下为执行Lighthouse的关键操作步骤
const exec = require('child_process').exec
const execStr = 'CHROME_PATH=$(which google-chrome) lighthouse http://baidu.com --disable-device-emulation=true --emulated-form-factor=desktop --output=json --locale=zh-CN --chrome-flags="--headless --no-sandbox"'
exec(execStr , {
encoding: 'utf8',
timeout: 0,
maxBuffer: 5000 * 1024,
killSignal: 'SIGTERM'
}, function (error, stdout, stderr) {
if (error) {
reject(error)
} else {
resolve(stdout)
}
})
拿到结果json后,选择需要上传的数据,上传至接口即可。