UNPKG

web-performance-monitor-sdk

Version:

A modern, lightweight performance monitoring SDK for web applications. Monitor Core Web Vitals (LCP, FCP, FID, CLS, TTFB) with sendBeacon support.

346 lines (269 loc) 7.96 kB
# Performance Monitor 使用指南 ## 快速开始 ### 1. 安装 ```bash # 使用 npm npm install performance-monitor # 使用 pnpm pnpm add performance-monitor # 使用 yarn yarn add performance-monitor ``` ### 2. 基础使用 #### 方式一:输出到控制台(最简单) ```javascript import PerformanceMonitor from 'performance-monitor'; // 初始化监控器 const monitor = new PerformanceMonitor({ output: 'console', // 输出到控制台 debug: true // 开启调试模式 }); // 性能指标会自动收集并输出到控制台 ``` #### 方式二:发送到服务器(推荐用于生产环境) ```javascript import PerformanceMonitor from 'performance-monitor'; const monitor = new PerformanceMonitor({ output: 'sendBeacon', // 使用sendBeacon发送 endpoint: 'https://your-api.com/performance', // 你的API地址 sampleRate: 0.1, // 10%采样率,减少服务器压力 enableErrorTracking: true // 开启错误监控 }); ``` #### 方式三:自定义处理 ```javascript import PerformanceMonitor from 'performance-monitor'; const monitor = new PerformanceMonitor({ output: 'custom', customReporter: (metrics) => { // 你可以在这里做任何处理 console.log('性能数据:', metrics); // 发送到你的分析平台 // analytics.track('performance', metrics); // 或者发送到自己的服务器 // fetch('/api/metrics', { // method: 'POST', // body: JSON.stringify(metrics) // }); } }); ``` ### 3. HTML中直接使用(无需构建工具) ```html <!DOCTYPE html> <html> <head> <title>我的网站</title> </head> <body> <h1>欢迎来到我的网站</h1> <!-- 引入性能监控SDK --> <script src="https://unpkg.com/performance-monitor@2.0.0/dist/index.umd.js"></script> <script> // 初始化性能监控 const monitor = new PerformanceMonitor.PerformanceMonitor({ output: 'console', debug: true }); // 页面加载完成后查看性能数据 window.addEventListener('load', function() { setTimeout(function() { const metrics = monitor.getMetrics(); console.log('页面性能指标:', metrics); }, 2000); }); </script> </body> </html> ``` ## 配置选项详解 ```javascript const monitor = new PerformanceMonitor({ // 输出方式:'console' | 'sendBeacon' | 'fetch' | 'custom' output: 'console', // API端点(当使用sendBeacon或fetch时需要) endpoint: 'https://your-api.com/performance', // 自定义处理函数(当使用custom时需要) customReporter: (metrics) => { console.log(metrics); }, // 是否启用错误监控 enableErrorTracking: false, // 是否启用资源监控 enableResourceTiming: false, // 采样率(0-1之间) sampleRate: 1, // 1表示100%,0.1表示10% // 是否开启调试模式 debug: false }); ``` ## API方法 ### getMetrics() 获取当前收集的性能指标(简单版本) ```javascript const metrics = monitor.getMetrics(); console.log(metrics); // 输出: { fcp: 1200, lcp: 2500, fid: 50, cls: 0.05, ttfb: 300 } ``` ### getDetailedMetrics() 获取详细的性能指标信息(包含评分) ```javascript const detailedMetrics = monitor.getDetailedMetrics(); console.log(detailedMetrics); // 输出: // { // fcp: { value: 1200, score: 'good', timestamp: 1640995200000 }, // lcp: { value: 2500, score: 'good', timestamp: 1640995201000 } // } ``` ### reportMetrics() 手动报告性能指标 ```javascript // 当你想手动发送数据时调用 monitor.reportMetrics(); ``` ### getErrorCount() 获取错误统计数量 ```javascript const errorCount = monitor.getErrorCount(); console.log(`总共发生了 ${errorCount} 个错误`); ``` ### isReady() 检查监控器是否已初始化 ```javascript if (monitor.isReady()) { console.log('监控器运行正常'); } ``` ### disconnect() 停止性能监控 ```javascript // 当不再需要监控时调用 monitor.disconnect(); ``` ## 实际应用场景 ### 场景1:监控React应用 ```javascript // App.js import React, { useEffect } from 'react'; import PerformanceMonitor from 'performance-monitor'; function App() { useEffect(() => { // 初始化性能监控 const monitor = new PerformanceMonitor({ output: 'fetch', endpoint: '/api/performance', enableErrorTracking: true, sampleRate: 0.1 }); // 页面加载完成后发送数据 window.addEventListener('load', () => { setTimeout(() => { monitor.reportMetrics(); }, 3000); }); return () => { monitor.disconnect(); }; }, []); return ( <div className="App"> <h1>我的React应用</h1> </div> ); } export default App; ``` ### 场景2:监控Vue应用 ```javascript // main.js import { createApp } from 'vue'; import App from './App.vue'; import PerformanceMonitor from 'performance-monitor'; // 初始化性能监控 const monitor = new PerformanceMonitor({ output: 'sendBeacon', endpoint: 'https://analytics.yoursite.com/performance', enableErrorTracking: true }); // 创建应用 const app = createApp(App); app.mount('#app'); // 页面加载完成后发送性能数据 window.addEventListener('load', () => { setTimeout(() => { const metrics = monitor.getMetrics(); console.log('Vue应用性能指标:', metrics); }, 2000); }); ``` ### 场景3:与Google Analytics集成 ```javascript import PerformanceMonitor from 'performance-monitor'; const monitor = new PerformanceMonitor({ output: 'custom', customReporter: (metrics) => { // 发送到Google Analytics Object.entries(metrics).forEach(([key, detail]) => { gtag('event', 'performance', { event_category: 'Web Vitals', event_label: key, value: Math.round(detail.value), non_interaction: true }); }); }, enableErrorTracking: true }); ``` ### 场景4:监控单页应用的路由切换 ```javascript import PerformanceMonitor from 'performance-monitor'; // 初始化 const monitor = new PerformanceMonitor({ output: 'console', debug: true }); // 监听路由变化(以React Router为例) import { useEffect } from 'react'; import { useLocation } from 'react-router-dom'; function usePerformanceMonitoring() { const location = useLocation(); useEffect(() => { // 路由切换时记录性能数据 const metrics = monitor.getMetrics(); console.log(`路由 ${location.pathname} 的性能指标:`, metrics); }, [location]); } ``` ## 性能指标说明 | 指标 | 含义 | 良好 | 需要改进 | 差 | |------|------|------|----------|-----| | **FCP** | 首次内容绘制时间 | ≤ 1.8秒 | 1.8-3.0秒 | > 3.0秒 | | **LCP** | 最大内容绘制时间 | ≤ 2.5秒 | 2.5-4.0秒 | > 4.0秒 | | **FID** | 首次输入延迟 | ≤ 100毫秒 | 100-300毫秒 | > 300毫秒 | | **CLS** | 累积布局偏移 | ≤ 0.1 | 0.1-0.25 | > 0.25 | | **TTFB** | 首字节时间 | ≤ 800毫秒 | 800-1800毫秒 | > 1800毫秒 | ## 常见问题 ### Q: 为什么没有收集到指标? A: 请确保: 1. 浏览器支持PerformanceObserver API 2. 页面已经完全加载 3. 等待2-3秒让指标收集完成 ### Q: 如何减少对性能的影响? A: 1. 设置较低的采样率(如0.1表示10%) 2. 只在生产环境开启必要的监控 3. 使用sendBeacon而不是fetch ### Q: 支持哪些浏览器? A: 支持所有现代浏览器: - Chrome 60+ - Firefox 55+ - Safari 11+ - Edge 79+ ## 完整示例 查看项目中的 `example.html` 文件,里面有完整的使用示例和演示。 ## 需要帮助? - GitHub: https://github.com/your-username/performance-monitor - 文档: https://github.com/your-username/performance-monitor#readme - 问题反馈: https://github.com/your-username/performance-monitor/issues