lighthouse性能预算 (budget.json)(翻译)

1,571 阅读3分钟

原文:github.com/GoogleChrom…

使用性能预算来确定性能指标的阈值。budget.json支持三种类型的预算:

时间预算:为基于时间的性能指标确定阈值,如第一次内容绘制、最大首次输入延迟和速度索引。

资源计数:断言页面上资源数量的阈值。这些阈值可以根据资源类型或整个页面定义。

资源大小:断言页面上资源传输大小的阈值。这些阈值可以根据资源类型或整个页面定义。

如果已经配置了性能预算,lighthouse报告将包括“性能预算”部分。

要使绩效预算成为CI流程的一部分,请参阅Lighthouse CI

使用

lighthouse的CLI版本支持性能预算。使用:

1.创建budget.json文件。

2.从命令行运行Lighthouse时,传递--budget-path标志,然后传递到预算文件的路径,以便在类别超出预算时进行计算。

lighthouse https://youtube.com --budget-path=budget.json

budget.json

这个budget.json文件是包含一个或多个预算对象的数组。

[
  {
    "path": "/*",
    "options": {
       "firstPartyHostnames": ["*.my-site.com", "my-site.cdn.com"]
    },
    "timings": [
      {
        "metric": "interactive",
        "budget": 5000
      },
      {
        "metric": "first-meaningful-paint",
        "budget": 2000
      }
    ],
    "resourceSizes": [
      {
        "resourceType": "total",
        "budget": 500
      },
      {
        "resourceType": "script",
        "budget": 150
      }
    ],
    "resourceCounts": [
      {
        "resourceType": "third-party",
        "budget": 100
      }
    ]
  },
  {
    "options": {
       "firstPartyHostnames": ["*.my-site.com", "my-site.cdn.com"]
    },
    "path": "/checkout",
    "resourceSizes": [
      {
        "resourceType": "script",
        "budget": 200
      }
    ]
  }
]

进一步说明

时间预算

Lighthouse 6 & up

使用可选时间属性定义基于时间的性能指标的预算。在这种情况下,预算是以毫秒为单位定义的。

"timings": [
   {
         "metric": "interactive",
         "budget": 5000
   }
]

支持的时间指标:

  • first-contentful-paint
  • first-cpu-idle
  • interactive
  • first-meaningful-paint
  • max-potential-fid
  • estimated-input-latency
  • total-blocking-time
  • speed-index
  • largest-contentful-paint
  • cumulative-layout-shift

资源预算

使用可选的resourceSizes属性定义页面资源大小的预算。在这种情况下,预算以kibibytes(1kib=1024字节)定义。

"resourceSizes": [
   {
      "resourceType": "script",
      "budget": 300
   }
]

使用可选的resourceCounts属性定义页资源数量的预算。在这种情况下,预算定义在请求中。

"resourceCounts": [
   {
      "resourceType": "script",
      "budget": 10
   }
]

可以为以下资源类型设置预算。

  • document
  • font
  • image
  • media
  • other
  • script
  • stylesheet
  • third-party
  • total

使用path属性

Lighthouse 5.3 & up

path属性标识应用预算的页。这个字符串应该跟在robots.txt 格式。

如果未提供路径,则预算将应用于所有页面。

如果页面的URL路径与中多个预算的路径属性匹配budget.json,则应用最后匹配的预算。因此,全局预算(例如“path”:“/*”)应首先列在budget.json,然后是覆盖全局预算的预算(例如“path”:“/blog”)。

示例:

"path": "/"

结果:匹配所有URL路径。这相当于写“path”:“/*”

"path": "/articles"

结果:匹配以/articles开头的所有URL路径。例如,/articles和/articles/jun_02_2019.html

"path": "/store/*/details$"

结果:Matches/store/closes/item123/details但不匹配/store/details。

第三方资源的识别

Lighthouse 6 & up

options.firstparty主机名可用于指示哪些资源应被视为第一方。可以选择使用通配符来匹配主机名及其所有子域。

如果未设置此属性,则根域及其所有子域将被视为第一方。

"options": {
   "firstPartyHostnames": ["*.my-site.com", "my-site.cdn.com"]
}

例如:

"firstPartyHostnames": ["pets.com"]

结果:pets.com被认为是第一方,但是fish.pets.com不是。

"firstPartyHostnames": ["*.pets.com"]

结果:两者pets.com以及fish.pets.com被视为第一方。