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.

698 lines (573 loc) 16 kB
# Performance Monitor 配置说明 ## 📋 完整配置项 ```typescript const monitor = new PerformanceMonitor({ output?: 'console' | 'sendBeacon' | 'fetch' | 'custom'; endpoint?: string; customReporter?: (metrics: PerformanceMetrics) => void; enableErrorTracking?: boolean; enableResourceTiming?: boolean; sampleRate?: number; debug?: boolean; }); ``` ## 详细说明 ### 1. output - 输出方式 ⭐⭐⭐⭐⭐ **类型**:`'console' | 'sendBeacon' | 'fetch' | 'custom'` **默认值**:`'console'` **必填**:否 **作用**:决定性能数据如何输出和发送 #### 可选值详解 ##### `'console'` - 控制台输出 ```javascript { output: 'console' } ``` **适用场景**: - 开发环境调试 - 本地测试 - 快速查看性能数据 **优点**: - 直接在浏览器控制台看到数据 - 无需配置服务器 - 方便调试 **缺点**: - 不能用于生产环境 - 用户看不到数据 - 无法收集真实用户数据 **示例输出**: ``` [Performance Monitor] FCP: { value: 1200, score: 'good', timestamp: 1234567890 } [Performance Monitor] LCP: { value: 2500, score: 'good', timestamp: 1234567891 } ``` --- ##### `'sendBeacon'` - SendBeacon API 🎯推荐 ```javascript { output: 'sendBeacon', endpoint: 'https://your-api.com/performance' } ``` **适用场景**: - 生产环境(最推荐) - 需要收集真实用户数据 - 大规模部署 **优点**: - 不阻塞页面加载和卸载 - 即使用户关闭页面也能发送成功 - 浏览器原生支持,性能最佳 - 不影响用户体验 **缺点**: - 不能处理服务器响应 - 需要配置服务器端点 **浏览器支持**: - Chrome 39+ - Firefox 31+ - Safari 11.1+ - Edge 14+ **服务器端接收示例**(Node.js/Express): ```javascript app.post('/api/performance', (req, res) => { const metrics = req.body; console.log('收到性能数据:', metrics); // 保存到数据库 db.collection('performance').insertOne({ ...metrics, userAgent: req.headers['user-agent'], timestamp: new Date() }); res.sendStatus(204); // 无需返回内容 }); ``` --- ##### `'fetch'` - Fetch API ```javascript { output: 'fetch', endpoint: 'https://your-api.com/performance' } ``` **适用场景**: - 需要处理服务器响应 - 需要错误处理 - 需要自定义请求头 **优点**: - 可以等待和处理响应 - 支持Promise - 可以自定义请求配置 **缺点**: - 页面关闭时可能发送失败 - 会占用一定的资源 **请求格式**: ```javascript // 自动发送的请求 fetch('https://your-api.com/performance', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ fcp: { value: 1200, score: 'good', timestamp: 1234567890 }, lcp: { value: 2500, score: 'good', timestamp: 1234567891 } }), keepalive: true }); ``` --- ##### `'custom'` - 自定义处理 ```javascript { output: 'custom', customReporter: (metrics) => { // 你的自定义逻辑 console.log('收到指标:', metrics); // 发送到Google Analytics gtag('event', 'performance', metrics); // 或者发送到其他服务 analytics.track('performance', metrics); } } ``` **适用场景**: - 与现有分析系统集成 - 需要特殊处理逻辑 - 多平台同时上报 **优点**: - 完全可控 - 灵活性最高 - 可以同时发送到多个平台 **示例:集成Google Analytics** ```javascript const monitor = new PerformanceMonitor({ output: 'custom', customReporter: (metrics) => { Object.entries(metrics).forEach(([key, detail]) => { gtag('event', 'web_vitals', { event_category: 'Performance', event_label: key.toUpperCase(), value: Math.round(detail.value), metric_rating: detail.score }); }); } }); ``` --- ### 2. endpoint - API端点地址 ⭐⭐⭐⭐ **类型**:`string` **默认值**:`undefined` **必填**:当使用 `sendBeacon` `fetch` 时必填 **作用**:指定接收性能数据的服务器地址 **示例**: ```javascript { output: 'sendBeacon', endpoint: 'https://analytics.yoursite.com/api/performance' } ``` **注意事项**: - 必须是完整的URL(包含协议) - 建议使用HTTPS - 需要配置CORS(跨域请求) - ⚠️ 确保API能处理POST请求 **CORS配置示例**(Node.js): ```javascript app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'POST'); res.header('Access-Control-Allow-Headers', 'Content-Type'); next(); }); ``` --- ### 3. customReporter - 自定义上报函数 ⭐⭐⭐ **类型**:`(metrics: PerformanceMetrics) => void` **默认值**:`undefined` **必填**:当使用 `custom` 输出方式时必填 **作用**:自定义处理性能数据的函数 **参数说明**: ```typescript interface PerformanceMetrics { fcp?: number; // First Contentful Paint (毫秒) lcp?: number; // Largest Contentful Paint (毫秒) fid?: number; // First Input Delay (毫秒) cls?: number; // Cumulative Layout Shift (无单位) ttfb?: number; // Time to First Byte (毫秒) } ``` **示例1:发送到多个平台** ```javascript { output: 'custom', customReporter: (metrics) => { // 发送到自己的API fetch('/api/metrics', { method: 'POST', body: JSON.stringify(metrics) }); // 同时发送到Google Analytics gtag('event', 'performance', metrics); // 还可以发送到其他服务 Sentry.captureMessage('Performance Metrics', { level: 'info', extra: metrics }); } } ``` **示例2:添加自定义数据** ```javascript { output: 'custom', customReporter: (metrics) => { const data = { ...metrics, userId: getCurrentUserId(), page: window.location.pathname, device: getDeviceType(), timestamp: Date.now() }; fetch('/api/performance', { method: 'POST', body: JSON.stringify(data) }); } } ``` --- ### 4. sampleRate - 采样率 ⭐⭐⭐⭐⭐ **类型**:`number` **默认值**:`1` **取值范围**:`0` `1` **必填**:否 **作用**:控制多少比例的用户会被监控,用于节省成本 **采样规则**: - `1` = 100%,所有用户都会被监控 - `0.5` = 50%,一半用户会被监控 - `0.1` = 10%,十分之一用户会被监控 - `0.01` = 1%,百分之一用户会被监控 **成本对比**: ``` 假设你的网站每天有 100 访问量 sampleRate: 1.0 每天收集 1,000,000 条数据 💰💰💰💰💰 sampleRate: 0.5 每天收集 500,000 条数据 💰💰💰 sampleRate: 0.1 每天收集 100,000 条数据 💰 sampleRate: 0.01 每天收集 10,000 条数据 💡 即使只有1%的采样率,10,000条数据也完全够分析性能趋势了! ``` **推荐配置**: | 日访问量 | 推荐采样率 | 每日数据量 | 说明 | |---------|-----------|-----------|------| | < 1 | `1.0` (100%) | < 1 | 流量小,全部监控 | | 1 - 10 | `0.5` (50%) | 0.5 - 5 | 适中,可以全监控或减半 | | 10 - 100 | `0.1` (10%) | 1 - 10 | 较大,10%足够 | | > 100 | `0.01` (1%) | > 1 | 超大,1%已有足够样本 | **示例**: ```javascript // 小型网站/个人项目 { sampleRate: 1.0 // 全部监控 } // 中型网站 { sampleRate: 0.1 // 10%监控 } // 大型网站 { sampleRate: 0.01 // 1%监控 } ``` **采样是随机的吗?** 是的,每次页面加载时会随机决定是否监控: ```javascript // 内部实现 if (Math.random() < sampleRate) { // 开始监控 } else { // 不监控 } ``` --- ### 5. enableErrorTracking - 错误监控 ⭐⭐⭐⭐ **类型**:`boolean` **默认值**:`false` **必填**:否 **作用**:是否开启JavaScript错误和资源加载错误的监控 **监控内容**: #### 1. JavaScript运行时错误 ```javascript // 这些错误会被捕获 throw new Error('出错了'); undefined.property; // TypeError JSON.parse('invalid'); // SyntaxError ``` #### 2. Promise Rejection错误 ```javascript // 这些Promise错误会被捕获 Promise.reject('失败了'); fetch('/api').catch(e => {}); async function() { throw new Error('async错误'); } ``` #### 3. 资源加载失败 ```html <!-- 这些加载失败会被捕获 --> <img src="404.jpg"> <script src="missing.js"></script> <link href="missing.css"> ``` **错误数据格式**: ```javascript { type: 'javascript-error', message: '错误信息', filename: 'app.js', lineno: 123, colno: 45, stack: '错误堆栈', timestamp: 1234567890, userAgent: 'Mozilla/5.0...', url: 'https://yoursite.com/page' } ``` **使用场景**: ```javascript // 开启错误监控 const monitor = new PerformanceMonitor({ output: 'sendBeacon', endpoint: '/api/errors', enableErrorTracking: true // 开启 }); // 查看错误统计 const errorCount = monitor.getErrorCount(); console.log(`共发生了 ${errorCount} 个错误`); ``` **注意事项**: - ⚠️ 会增加一些数据量 - ⚠️ 不会影响现有的错误处理逻辑 - ⚠️ 只监控,不阻止错误发生 - 可以与Sentry等错误监控工具配合使用 --- ### 6. enableResourceTiming - 资源监控 ⭐⭐ **类型**:`boolean` **默认值**:`false` **必填**:否 **作用**:是否监控页面所有资源的加载性能 **监控内容**: - 图片加载时间(.jpg, .png, .gif, .webp等) - CSS文件加载时间 - JavaScript文件加载时间 - 字体文件加载时间 - API请求时间(XHR, Fetch) **数据量警告**: ``` 一个普通页面可能加载: - 10+ 图片 - 5+ CSS文件 - 10+ JS文件 - 3+ 字体文件 - N+ API请求 每个资源都会生成一条数据! ``` **适用场景**: - 需要优化资源加载的专项分析 - 临时性能调试 - 常规生产环境监控(不推荐) **示例**: ```javascript // 一般不需要开启 { enableResourceTiming: false // 默认关闭 } // 只在需要时开启 { enableResourceTiming: true, sampleRate: 0.01 // 配合极低采样率使用 } ``` **建议**: - ⚠️ 通常保持关闭状态 - ⚠️ 如需开启,配合低采样率 - 使用浏览器DevTools查看资源性能更方便 --- ### 7. debug - 调试模式 ⭐⭐⭐ **类型**:`boolean` **默认值**:`false` **必填**:否 **作用**:是否输出详细的调试日志 **日志内容**: ```javascript // debug: true 时的输出 [Performance Monitor] Performance monitoring initialized successfully [Performance Monitor] FCP 指标收集完成: 1200ms [Performance Monitor] LCP 指标收集完成: 2500ms [Performance Monitor] FID 指标收集完成: 50ms [Performance Monitor] CLS 指标收集完成: 0.05 [Performance Monitor] TTFB 指标收集完成: 300ms [Performance Monitor] 显示性能指标: 5 个指标 ``` **使用建议**: ```javascript // 开发环境 const monitor = new PerformanceMonitor({ debug: true // 开启,方便调试 }); // 生产环境 const monitor = new PerformanceMonitor({ debug: false // 关闭,减少日志 }); // 根据环境自动配置 const monitor = new PerformanceMonitor({ debug: process.env.NODE_ENV === 'development' }); ``` **性能影响**: - 开启debug对性能影响极小 - 主要是增加控制台输出 - 生产环境建议关闭 --- ## 🎯 最佳实践配置 ### 1. 开发环境配置 ```javascript const monitor = new PerformanceMonitor({ output: 'console', // 控制台查看 enableErrorTracking: true, // 捕获错误 enableResourceTiming: true, // 查看资源性能 sampleRate: 1, // 全部监控 debug: true // 详细日志 }); ``` ### 2. 生产环境配置(小型网站) ```javascript const monitor = new PerformanceMonitor({ output: 'sendBeacon', endpoint: 'https://api.yoursite.com/performance', enableErrorTracking: true, enableResourceTiming: false, sampleRate: 1, // 流量小可以全监控 debug: false }); ``` ### 3. 生产环境配置(中型网站) ```javascript const monitor = new PerformanceMonitor({ output: 'sendBeacon', endpoint: 'https://api.yoursite.com/performance', enableErrorTracking: true, enableResourceTiming: false, sampleRate: 0.1, // 10%采样 debug: false }); ``` ### 4. 生产环境配置(大型网站) ```javascript const monitor = new PerformanceMonitor({ output: 'sendBeacon', endpoint: 'https://analytics.yoursite.com/perf', enableErrorTracking: true, enableResourceTiming: false, sampleRate: 0.01, // 1%采样 debug: false }); ``` ### 5. 与现有系统集成 ```javascript const monitor = new PerformanceMonitor({ output: 'custom', customReporter: (metrics) => { // 发送到自己的API fetch('/api/metrics', { method: 'POST', body: JSON.stringify({ ...metrics, userId: getCurrentUserId(), page: window.location.pathname }) }); // 同时发送到Google Analytics gtag('event', 'performance', metrics); }, enableErrorTracking: true, sampleRate: 0.1, debug: false }); ``` --- ## 🔍 配置验证 SDK会自动验证配置参数: ```javascript // 错误的配置 new PerformanceMonitor({ sampleRate: 1.5 // 错误:必须在0-1之间 }); // 抛出错误: sampleRate must be a number between 0 and 1 new PerformanceMonitor({ endpoint: 123 // 错误:必须是字符串 }); // 抛出错误: endpoint must be a string new PerformanceMonitor({ customReporter: 'not a function' // 错误:必须是函数 }); // 抛出错误: customReporter must be a function ``` --- ## 📊 配置选择流程图 ``` 开始 你在开发还是生产环境? ├─ 开发 output: 'console', debug: true └─ 生产 有自己的服务器吗? ├─ output: 'sendBeacon', endpoint: 'your-api' └─ 没有 output: 'custom', 集成第三方服务 每天访问量多少? ├─ < 1 sampleRate: 1.0 ├─ 1-10 sampleRate: 0.5 ├─ 10-100 sampleRate: 0.1 └─ > 100 sampleRate: 0.01 需要错误监控吗? ├─ 需要 enableErrorTracking: true └─ 不需要 enableErrorTracking: false 完成! ``` --- ## 💡 常见问题 ### Q: 我应该设置多少采样率? A: - 小网站(日访问<1万):`1.0`(100%) - 中网站(日访问1-10万):`0.1`(10%) - 大网站(日访问>100万):`0.01`(1%) ### Q: sendBeacon和fetch有什么区别? A: - **sendBeacon**:不阻塞页面,页面关闭也能发送,推荐生产环境使用 - **fetch**:可以处理响应,但页面关闭可能发送失败 ### Q: 我需要开启enableResourceTiming吗? A: 通常不需要。它会产生大量数据,除非你在做专项的资源加载优化。 ### Q: debug模式会影响性能吗? A: 几乎不会。主要是增加控制台日志输出,对实际性能影响可忽略。 ### Q: 可以动态修改配置吗? A: 可以,使用 `monitor.updateConfig()` 方法: ```javascript monitor.updateConfig({ debug: true, sampleRate: 0.5 }); ``` --- ## 📝 总结 | 配置项 | 重要性 | 开发环境 | 生产环境 | 说明 | |--------|--------|----------|----------|------| | output | ⭐⭐⭐⭐⭐ | console | sendBeacon | 必须配置 | | endpoint | ⭐⭐⭐⭐ | - | 必填 | sendBeacon/fetch时需要 | | sampleRate | ⭐⭐⭐⭐⭐ | 1.0 | 0.01-0.1 | 节省成本 | | enableErrorTracking | ⭐⭐⭐⭐ | true | true | 推荐开启 | | enableResourceTiming | ⭐⭐ | true | false | 通常不需要 | | debug | ⭐⭐⭐ | true | false | 开发时开启 | | customReporter | ⭐⭐⭐ | - | 可选 | 自定义需求时使用 |