Lighthouse分析web应用程序和web页面,收集关于开发人员最佳实践的现代性能指标和见解,让开发人员根据生成的评估页面,来进行网站优化和完善,提高用户体验。
-
chrome中使用
在F12中,打开就能看到
- 使用lighthouse的cli
首先下载nodejs,不赘述了
在cmd中输入
#全局安装
npm install -g lighthouse
#执行,此处的file.json是配置cookie等请求头信息
lighthouse https://www.baidu.com/ --locale=zh-CH --preset=desktop --output-path=./reports/report.html --extra-headers=file.json --only-categories=performance,accessibility,best-practices,seo
- 嵌入在代码中,使用node执行
同上,下载nodejs
在cmd中输入
npm init
npm install lighthouse chrome-launcher --save
比如新建文件s.js
const fs = require('fs');
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
(async () => {
const chrome = await chromeLauncher.launch({chromeFlags: ['--headless']});
//lighthouse运行的一些配置信息
const flag={
onlyCategories: ['performance','accessibility','best-practices','seo',]
,locale:'zh-CH',
port:chrome.port,
preset: 'desktop',
verbose: false,
quiet: false,
'save-assets': false,
saveAssets: false,
'list-all-audits': false,
listAllAudits: false,
'list-trace-categories': false,
listTraceCategories: false,
'print-config': false,
printConfig: false,
'chrome-flags': '',
chromeFlags: '',
enableErrorReporting: false,
output: 'html' ,
view: false,
'chrome-ignore-default-flags': false,
chromeIgnoreDefaultFlags: false,
logLevel: 'info'
}
option={
extends: 'lighthouse:default',
settings: {
formFactor: 'desktop',
throttling: {
rttMs: 40,
throughputKbps: 10240,
cpuSlowdownMultiplier: 1,
requestLatencyMs: 0,
downloadThroughputKbps: 0,
uploadThroughputKbps: 0
},
screenEmulation: {
mobile: false,
width: 1350,
height: 940,
deviceScaleFactor: 1,
disabled: false
},
emulatedUserAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4420.0 Safari/537.36 Chrome-Lighthouse'
}
}
//执行lighthouse得到执行结果,执行结果是一个JS对象
const runnerResult = await lighthouse('https://www.baidu.com', flag,option);
//通过lighthouse的运行结果的report属性拿到运行报告,运行报告是一个string
const reportHtml = runnerResult.report;
//生成结果文件
fs.writeFileSync('lhreport.html', reportHtml);
//关闭Chrome浏览器进程
await chrome.kill();
})();
然后执行
node s.js
我使用的是第三种,为了结合selenium使用:
require('chromedriver');
const fs = require('fs');
var webdriver = require('selenium-webdriver');
By = webdriver.By;
var driver = new webdriver.Builder()
.forBrowser('chrome')
.build();
var addr = ''
driver.getCapabilities().then((a) => {
(async () => {
addr = a['map_'].get('goog:chromeOptions')['debuggerAddress']
// console.log(addr)
port = addr.split(':')[1] //此处为了获得devtools的端口
...之后可以写相关脚本然后再调用lighthouse