如何调用PageSpeed Insights API仅获取Web Vitals数据以提升性能?
仅获取PageSpeed Insights的核心Web Vitals数据(无需Lighthouse结果)
核心解决思路
Pagespeed UI顶部的核心Web Vitals是谷歌预计算并缓存的数据,不需要实时运行Lighthouse扫描。要快速拿到这些数据,关键是用Google API的fields参数直接指定返回loadingExperience和originLoadingExperience,API会跳过Lighthouse诊断流程,直接返回预存的Web Vitals数据,耗时能压缩到几秒内。
1. 直接API调用实现
构造请求时添加fields参数,明确只索要需要的字段,示例格式如下:
GET https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=你的目标URL&key=你的API密钥&strategy=mobile&fields=loadingExperience,originLoadingExperience
strategy:可选值desktop或mobile,指定获取对应设备的Vitals数据fields:严格指定返回的字段,API会跳过Lighthouse扫描,直接返回预存数据
2. Node/TS googleapis库实现
先安装依赖:
npm install googleapis # 或使用yarn yarn add googleapis
TypeScript代码示例:
import { google } from 'googleapis'; const pagespeed = google.pagespeedonline('v5'); async function getWebVitals(url: string, apiKey: string) { const response = await pagespeed.pagespeedapi.runpagespeed({ url, key: apiKey, strategy: 'mobile', // 可选desktop fields: 'loadingExperience,originLoadingExperience' // 关键参数 }); console.log('核心Web Vitals数据:', response.data); } // 调用示例 getWebVitals('https://你的目标URL.com', '你的API密钥');
为什么category参数没用?
category参数的作用是指定Lighthouse扫描的分类,即使只选performance,API依然会完整运行Lighthouse诊断,所以耗时还是15-20秒。而fields参数是直接告诉API只返回预存的Web Vitals数据,不需要执行Lighthouse扫描,这才是提升速度的关键。
内容的提问来源于stack exchange,提问作者Pinguin Dirk
相关产品推荐
相关产品推荐

