一個站點的性能表現直接影響了用戶體驗,衡量站點的性能指標工具有很多蝗岖,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赞赖,根據自身需求設置好定時任務的執(zhí)行間隔即可。
以下為執(zhí)行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后冤灾,選擇需要上傳的數據前域,上傳至接口即可。