获取网页首屏加载时间

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

相关推荐
cll_869241891几秒前
一个好看的Wordpress博客文字css样式
前端·css·ui
糖果店的幽灵5 分钟前
langgraph分支之 - 动态分支(Dynamic Branch)
java·前端·javascript·人工智能·langgraph
meilindehuzi_a15 分钟前
Workflow 与 Agent 有什么区别:从 LangChain 流水线到智能体决策
前端·人工智能
Bad_Shepherd21 分钟前
vue-element-plus-admin添加自定义svg图标,并且图标选择组件可选自定义图标
vue.js·elementui·前端框架
这是个栗子23 分钟前
前端开发中的常用工具函数(九)
开发语言·javascript·ecmascript·at
吃糖的小孩2 小时前
从只读页面到可控真实探针:我如何给 Owner Console 加手动诊断
前端
谷无姜2 小时前
为什么你的性能优化无效?可能是"木桶效应"在作祟
前端·性能优化
雾非雾2 小时前
《基于具身交互智能数字人技术:如何打造AI数字人宣讲平台"红厅智播”》
前端
Revolution612 小时前
一段 JavaScript 代码执行时,到底发生了什么
前端·javascript
智能起源2 小时前
关于元素层级过多,导致压祯的问题(使用winform或者WPF应用的webview组件嵌套网页时,动效卡顿问题)
前端