获取网页首屏加载时间

1. 使用 Performance API(推荐)

复制代码
// 方法1:获取首屏加载时间(First Contentful Paint)
const performance = window.performance || window.mozPerformance || 
                   window.msPerformance || window.webkitPerformance;

if (performance && performance.getEntriesByName) {
    const fcpEntry = performance.getEntriesByName('first-contentful-paint')[0];
    if (fcpEntry) {
        console.log('首屏加载时间(FCP):', fcpEntry.startTime + 'ms');
    }
}

// 方法2:获取所有性能指标
window.addEventListener('load', () => {
    setTimeout(() => {
        const perfData = performance.getEntriesByType('navigation')[0];
        const paintTimings = performance.getEntriesByType('paint');
        
        if (perfData) {
            console.log('DNS查询时间:', perfData.domainLookupEnd - perfData.domainLookupStart + 'ms');
            console.log('TCP连接时间:', perfData.connectEnd - perfData.connectStart + 'ms');
            console.log('请求响应时间:', perfData.responseEnd - perfData.requestStart + 'ms');
            console.log('DOM解析时间:', perfData.domComplete - perfData.domInteractive + 'ms');
            console.log('白屏时间:', perfData.responseStart - perfData.navigationStart + 'ms');
        }
        
        // 获取各种关键时间点
        paintTimings.forEach(paint => {
            if (paint.name === 'first-paint') {
                console.log('首次绘制(FP):', paint.startTime + 'ms');
            }
            if (paint.name === 'first-contentful-paint') {
                console.log('首次内容绘制(FCP):', paint.startTime + 'ms');
            }
        });
        
        // LCP(最大内容绘制)
        new PerformanceObserver((entryList) => {
            const entries = entryList.getEntries();
            const lastEntry = entries[entries.length - 1];
            console.log('最大内容绘制(LCP):', lastEntry.startTime + 'ms');
        }).observe({ type: 'largest-contentful-paint', buffered: true });
    }, 0);
});

2. 使用 web-vitals 库(Google官方推荐)

复制代码
// 安装:npm install web-vitals
import { getFCP, getLCP, getCLS } from 'web-vitals';

// 获取首屏时间相关指标
getFCP(console.log);  // 首次内容绘制
getLCP(console.log);  // 最大内容绘制

3. Chrome DevTools 查看

  1. 打开 Chrome DevTools(F12)

  2. 进入 Performance 面板

  3. 点击录制按钮,刷新页面

  4. 查看 Timings 部分:

    • FP (First Paint):首次绘制

    • FCP (First Contentful Paint):首次内容绘制

    • LCP (Largest Contentful Paint):最大内容绘制

4. 使用 Lighthouse 工具

复制代码
# 命令行方式
npx lighthouse https://example.com --output=json --output-path=./report.json

# 或使用 Chrome DevTools 的 Lighthouse 面板

5. 浏览器扩展工具

  • Lighthouse(Chrome扩展)

  • Web Vitals(Chrome扩展)

  • PageSpeed Insights

6. 服务端监控(Node.js示例)

复制代码
const puppeteer = require('puppeteer');

async function getFirstScreenTime(url) {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    
    // 监听性能指标
    await page.evaluateOnNewDocument(() => {
        window.performanceMetrics = {};
        const observer = new PerformanceObserver((list) => {
            for (const entry of list.getEntries()) {
                if (entry.name === 'first-contentful-paint') {
                    window.performanceMetrics.fcp = entry.startTime;
                }
                if (entry.entryType === 'largest-contentful-paint') {
                    window.performanceMetrics.lcp = entry.startTime;
                }
            }
        });
        observer.observe({ entryTypes: ['paint', 'largest-contentful-paint'] });
    });
    
    await page.goto(url, { waitUntil: 'networkidle0' });
    
    const metrics = await page.evaluate(() => window.performanceMetrics);
    console.log('FCP:', metrics.fcp, 'ms');
    console.log('LCP:', metrics.lcp, 'ms');
    
    await browser.close();
}

关键指标说明

指标 含义 优秀标准
FP 首次绘制(任何像素点) < 1s
FCP 首次内容绘制(文本/图片等) < 1.8s
LCP 最大内容绘制 < 2.5s
TTI 可交互时间 < 3.8s

建议

  1. 生产环境监控:使用 web-vitals + Google Analytics 或监控平台

  2. 开发阶段:使用 Chrome DevTools 和 Lighthouse

  3. 自动化测试:使用 Puppeteer/Playwright 集成到 CI/CD

相关推荐
烟锁池塘柳02 小时前
【已解决】Google Chrome 浏览器报错 STATUS_ACCESS_VIOLATION 的解决方案
前端·chrome
速易达网络2 小时前
基于RuoYi-Vue 框架美妆系统
前端·javascript·vue.js
LYS_06182 小时前
RM赛事C型板九轴IMU解算(4)(卡尔曼滤波)
c语言·开发语言·前端·卡尔曼滤波
We་ct3 小时前
LeetCode 151. 反转字符串中的单词:两种解法深度剖析
前端·算法·leetcode·typescript
yinmaisoft4 小时前
JNPF 表单模板实操:高效复用表单设计指南
前端·javascript·html
37方寸4 小时前
前端基础知识(JavaScript)
开发语言·前端·javascript
Whisper_Sy4 小时前
Flutter for OpenHarmony移动数据使用监管助手App实战 - 应用列表实现
android·开发语言·javascript·flutter·php
json{shen:"jing"}5 小时前
1. 两数之和
前端·javascript·数据库
github.com/starRTC5 小时前
Claude Code中英文系列教程19:使用subagent子代理与创建自定义子代理【重要】
前端·javascript·数据库