使用Puppeteer和Chrome DevTools协议,如何获取4个性能计时指标?

时间:2019-08-20 16:59:35

标签: google-chrome-devtools puppeteer chrome-devtools-protocol

要创建以下屏幕截图,我已打开Chrome开发者工具,选择“性能”标签,开始录制,打开https://www.ted.com,然后停止录制。这是我看到的:

enter image description here

我如何以编程方式使用Puppeteer和潜在的Chrome DevTools Protocol,在屏幕快照中圈出4个指标?

1 个答案:

答案 0 :(得分:1)

您可以尝试

 const perfEntries = JSON.parse(
        await page.evaluate(() => JSON.stringify(performance.toJSON()))
    );
    const paints = await page.evaluate(_ => {
        const result = {};
        performance.getEntriesByType('paint').map(entry => {
            result[entry.name] = entry.startTime;
        });
        return result;
    });

    for (const [key, val] of Object.entries(paints)) {
        console.log(`${key}: ${Math.round(val)}ms`);
    }

    console.log('domContentLoadedEventEnd :' + `${Math.round(perfEntries.timing.domContentLoadedEventEnd) - Math.round(perfEntries.timeOrigin)}ms`);
    console.log('domComplete :' + `${ Math.round(perfEntries.timing.domComplete) - Math.round(perfEntries.timeOrigin)}ms`);
    console.log('loadEventEnd :' + `${Math.round(perfEntries.timing.loadEventEnd) - Math.round(perfEntries.timeOrigin)}ms`);

输出:

first-paint: 927ms
first-contentful-paint: 927ms
domContentLoadedEventEnd :1409ms
domComplete :4103ms
loadEventEnd :4183ms