• 如何使用Chrome的lighthouse实现自定义检测
  • 发布于 2个月前
  • 570 热度
    0 评论
  • Storm
  • 0 粉丝 37 篇博客
  •   
Chrome的lighthouse大家想必非常熟悉,常被用来做web页面的检测,从performance、best-practice到seo等方面,其都能为我们给出详细的检测结果。如果需要自定义检测数据可以怎么做呢?我们可以把进行自定义检测这一系列的工作流程简单想象为:
1. 将启动的浏览器的端口号以及对应自定义配置传给lighthouse,随后lighthouse开始工作
2. lighthouse先通过收集器(gatherer)来收集页面中的数据,随后将数据交给审查器
3. 审查器(audit)根据自己的规则处理数据,给出结果和对应的分数
4. 最后收集所有的审查结果,输出分数以及根据相应细节得出的建议,得到结果

下面就以一个收集页面加载图片数据为例说明。

自定义配置
通过额外传入配置config完成自定义配置,
const config = require('./custom/config');
const options = {
    logLevel: 'info',
    output: 'html',
    onlyCategories: ['performance', 'accessibility', 'best-practices', 'pwa', 'seo'],
    port: chrome.port,
};
const runnerResult = await lighthouse(
  'https://goofish.com',
  options,
  config // 新增的自定义配置
);
传入自定义收集器(gatherer)与审查器(audit)
// main.js
const config = require('./custom/config');

// config.js
const customResourceGatherer = require('./custom-resource-gatherer');
const customImageAudit = require('./custom-image-audit');

module.exports = {
  extends: 'lighthouse:default', // 'lighthouse:default' | undefined 是否继承默认配置
  settings: {
    onlyAudits: [
      'custom-image-audit',
    ],
  },
  passes: [
    {
      passName: 'defaultPass',
      gatherers: [
        customResourceGatherer, // 填入自己的收集器
      ]
    }
  ], // Object[] 采集器
  audits: [
    customImageAudit, // 填入自己的审查器
  ],
  categories: { // 这里是在lh报告上的展示的类别配置,和performance seo那些同级
    resource: {
      title: '静态资源', //定义一个叫静态资源的分组,下面规定有哪些审查器
      description: '展示页面上的所有资源情况',
      auditRefs: [
        {
          id: 'custom-image-audit',
          weight: 1,
          group: 'metrics'
        }
      ]
    },
  },
  groups: { // 这里是分组配置,属于类别的下一级
    metrics: {
      title: '资源',
    },
  },
}
编写收集器(gatherer)
定义收集数据的逻辑,在lighthouse启动后,会根据配置运行对应的收集器,收集器收集并返回数据。
const Gatherer = require('lighthouse').Gatherer;

class CustomResourceGatherer extends Gatherer {
  beforePass() {
    // 设定页面加载之前的采集内容
  }
  afterPass(options) {
    // 设定页面加载之后的采集内容
    const driver = options.driver; // 这里通过传入的变量注入自定义js,收集返回
    return driver
      .evaluateAsync(
        'JSON.stringify(window.performance.getEntriesByType("resource").filter(item => item.initiatorType === "img" && /(png|apng|gif|webp|jpg|jpeg)$/.test(item.name)))'
      )
      .then((loadMetrics) => {
        if (!loadMetrics) {
          throw new Error('无法获取资源信息');
        }
        return loadMetrics; // 返回收集的数据
      });
  }
}

编写审查器(audit)
定义数据处理逻辑,对收集器返回的数据进行数据逻辑处理,返回分数以及处理后的数据结果。
const Audit = require('lighthouse').Audit;

class CustomRequestAudit extends Audit {
  static get meta() {
    return {
      id: 'custom-image-audit', // 与配置中的audits数组内容对应
      title: '图片请求数据', // 分数达标时的展示标题(score大于等于90分)
      failureTitle: '资源加载失败', // 分数不达标时的展示标题
      description: '展示页面中加载的图片数据', // 子标题
      requiredArtifacts: ['CustomResourceGatherer'] // 所对应数据的采集器
    };
  }
  static audit(artifacts) {
    // 获得收集器的数据
    const loadMetrics = JSON.parse(artifacts.CustomResourceGatherer);
    if (!loadMetrics.length) {
      return {
        numericValue: 0,
        score: 1,
        displayValue: 'No image found'
      };
    }
    // 整理数据
    const data = loadMetrics.map((item) => {
      return {
        name: item.name,
        duration: `${parseInt(item.duration)}ms`,
        size: item.encodedBodySize
      }
    })
    const headings = [
      {
        key: 'name',
        itemType: 'url',
        text: '请求'
      },
      {
        key: 'duration',
        itemType: 'text',
        text: '耗时'
      },
      {
        key: 'size',
        itemType: 'text',
        text: '大小'
      }
    ];
    // 根据自定义规则返回得分
    return {
      score: 0.89,  // 自定定义分数
      // 这里可以使用audit提供的样式展示格式,通过传入数据来控制展示
      details: Audit.makeTableDetails(headings, data), 
      displayValue: `页面中有 ${loadMetrics.length} 个图片`,
      rawValue: '',
  }
}

结果展示

用户评论