npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

bili-web-performance-monitor

v1.1.1

Published

A comprehensive web performance monitoring tool for H5 and PC, with continuous monitoring and automatic optimization suggestions

Readme

Web Performance Monitor

🔍 一个全面的网页性能监控工具,支持 H5 和 PC 端,提供持续监控实时指标更新,自动收集性能指标并提供智能优化建议。

✨ 特性

  • 🔄 持续监控模式 ⭐️ NEW

    • 实时监听性能指标更新
    • 自动捕获 FID、LCP 等需要用户交互的指标
    • 定时生成性能报告
    • 灵活的监控控制(启动/停止)
  • 📊 全面的性能指标收集

    • Core Web Vitals (FCP, LCP, FID, CLS, TTFB, INP)
    • 导航时序数据
    • 资源加载性能
    • 内存使用情况
  • 📱 多平台支持

    • 自动检测设备类型 (PC/Mobile/Tablet)
    • 针对不同平台的性能阈值
    • 移动端和弱网环境特定优化建议
  • 💡 智能优化建议

    • 根据实际性能数据生成优化方案
    • 按优先级分类 (Critical/Important/Recommended)
    • 具体可行的改进措施
  • 📄 多种报告格式

    • 控制台输出
    • JSON 格式
    • HTML 可视化报告

📦 安装

npm install bili-web-performance-monitor

或使用 yarn:

yarn add bili-web-performance-monitor

🚀 快速开始

方式一:持续监控模式 ⭐️ 推荐

适用于需要实时跟踪性能指标的场景。

import WebPerformanceMonitor from 'bili-web-performance-monitor';

const monitor = new WebPerformanceMonitor({
  autoReport: false,  // 关闭自动控制台输出
  reportInterval: 30000,  // 每30秒生成一次报告
  onMetricsUpdate: (metrics) => {
    // 每次指标更新时触发(FCP、LCP、FID等)
    console.log('指标更新:', metrics);
    // 实时更新 UI 展示
  },
  onReport: (report) => {
    // 定时报告回调
    console.log('性能分数:', report.score.overall);
    // 上报到后端
  }
});

// 启动持续监控
monitor.startMonitoring();

// 随时获取当前指标
const currentMetrics = monitor.getCurrentMetrics();

// 手动生成报告
const report = monitor.generateCurrentReport();

// 页面卸载时停止监控
window.addEventListener('beforeunload', () => {
  monitor.stopMonitoring();
});

方式二:一次性监控(基础用法)

适用于快速性能检测,10秒超时后返回结果。

import WebPerformanceMonitor from 'bili-web-performance-monitor';

// 创建监控实例
const monitor = new WebPerformanceMonitor();

// 运行监控并获取报告
monitor.run().then(report => {
  console.log('性能报告:', report);
});

自定义配置

import WebPerformanceMonitor from 'bili-web-performance-monitor';

const monitor = new WebPerformanceMonitor({
  // 是否自动输出报告
  autoReport: true,

  // 报告格式: 'console' | 'json' | 'html'
  reportFormat: 'html',

  // 采样率 (0-1)
  sampleRate: 0.5,

  // 是否收集资源性能数据
  collectResources: true,

  // 自定义报告处理函数
  onReport: (report) => {
    // 发送到后端分析服务
    fetch('/api/performance', {
      method: 'POST',
      body: JSON.stringify(report)
    });
  }
});

monitor.run();

Vue 3 集成示例(持续监控)

// main.ts
import { createApp } from 'vue';
import App from './App.vue';
import WebPerformanceMonitor from 'bili-web-performance-monitor';

const app = createApp(App);
app.mount('#app');

// 启动持续监控
const monitor = new WebPerformanceMonitor({
  autoReport: false,
  reportInterval: 60000,  // 每60秒上报一次
  onMetricsUpdate: (metrics) => {
    // 实时更新性能面板
    console.log('LCP:', metrics.LCP, 'FID:', metrics.FID);
  },
  onReport: (report) => {
    // 上报到监控平台
    fetch('/api/performance', {
      method: 'POST',
      body: JSON.stringify(report)
    });
  }
});

monitor.startMonitoring();

// 页面卸载前停止并上报最终数据
window.addEventListener('beforeunload', () => {
  const finalReport = monitor.generateCurrentReport();
  if (finalReport) {
    navigator.sendBeacon('/api/performance/final', JSON.stringify(finalReport));
  }
  monitor.stopMonitoring();
});

React 集成示例(持续监控)

// App.tsx
import { useEffect, useState } from 'react';
import WebPerformanceMonitor from 'bili-web-performance-monitor';

function App() {
  const [metrics, setMetrics] = useState<any>(null);

  useEffect(() => {
    const monitor = new WebPerformanceMonitor({
      autoReport: false,
      onMetricsUpdate: (newMetrics) => {
        // 实时更新状态
        setMetrics(newMetrics);
      },
      onReport: (report) => {
        console.log('Performance Score:', report.score.overall);
      }
    });

    // 启动持续监控
    monitor.startMonitoring();

    // 清理函数
    return () => {
      monitor.stopMonitoring();
    };
  }, []);

  return (
    <div>
      <h1>Your App</h1>
      {metrics && (
        <div className="performance-panel">
          <div>LCP: {metrics.LCP ? `${metrics.LCP.toFixed(0)}ms` : 'N/A'}</div>
          <div>FID: {metrics.FID ? `${metrics.FID.toFixed(0)}ms` : 'N/A'}</div>
          <div>CLS: {metrics.CLS ? metrics.CLS.toFixed(3) : 'N/A'}</div>
        </div>
      )}
    </div>
  );
}

原生 JavaScript

<!DOCTYPE html>
<html>
<head>
  <title>Performance Monitor Demo</title>
</head>
<body>
  <h1>Web Performance Monitor</h1>

  <script type="module">
    import WebPerformanceMonitor from 'bili-web-performance-monitor';

    window.addEventListener('load', () => {
      setTimeout(() => {
        const monitor = new WebPerformanceMonitor({
          reportFormat: 'html'
        });

        monitor.run();
      }, 2000);
    });
  </script>
</body>
</html>

📊 性能指标说明

Core Web Vitals

| 指标 | 说明 | 良好阈值 (PC) | 良好阈值 (Mobile) | |------|------|---------------|-------------------| | FCP | First Contentful Paint - 首次内容绘制 | ≤ 1.0s | ≤ 1.8s | | LCP | Largest Contentful Paint - 最大内容绘制 | ≤ 2.0s | ≤ 2.5s | | FID | First Input Delay - 首次输入延迟 | ≤ 50ms | ≤ 100ms | | CLS | Cumulative Layout Shift - 累积布局偏移 | ≤ 0.1 | ≤ 0.1 | | TTFB | Time to First Byte - 首字节时间 | ≤ 600ms | ≤ 800ms |

其他指标

  • DOM Content Loaded: DOM 内容加载完成时间
  • Load Complete: 页面完全加载完成时间
  • Resources: 各类资源的加载性能
  • Memory: JavaScript 堆内存使用情况

💡 优化建议类型

报告会根据性能数据自动生成优化建议,按优先级分为三类:

🔴 Critical (严重)

需要立即处理的性能问题,严重影响用户体验。

🟡 Important (重要)

对性能有明显影响,建议优先优化。

🟢 Recommended (推荐)

可以进一步提升性能的优化建议。

🎯 常见优化建议

FCP/LCP 优化

  • 减少关键渲染路径中的资源
  • 使用 CDN 加速资源加载
  • 实施服务端渲染(SSR)或静态生成(SSG)
  • 优化图片(使用 WebP、AVIF 格式)
  • 对关键资源使用 <link rel="preload">

FID/INP 优化

  • 拆分长任务
  • 使用 Web Workers 处理计算密集型任务
  • 延迟加载非关键 JavaScript
  • 减少第三方脚本影响

CLS 优化

  • 为图片和视频设置明确尺寸
  • 避免在现有内容上方插入内容
  • 使用骨架屏
  • 预留广告位空间

移动端特定优化

  • 控制首屏资源在 1MB 以内
  • 使用响应式图片
  • 实施渐进式加载
  • 考虑使用 Service Worker

📄 API 文档

WebPerformanceMonitor

构造函数

constructor(config?: MonitorConfig)

MonitorConfig 配置项:

| 参数 | 类型 | 默认值 | 说明 | |------|------|--------|------| | autoReport | boolean | true | 是否自动输出报告 | | reportFormat | 'console' \| 'json' \| 'html' | 'console' | 报告输出格式 | | sampleRate | number | 1 | 采样率 (0-1) | | collectResources | boolean | true | 是否收集资源性能 | | onReport | (report: PerformanceReport) => void | () => {} | 自定义报告回调 | | reportInterval | number | 30000 | 定时报告间隔(毫秒),0表示禁用 | | onMetricsUpdate | (metrics: PerformanceMetrics) => void | () => {} | 指标更新回调 ⭐️ NEW |

方法

run()

运行性能监控(一次性),返回性能报告。10秒超时后返回结果。

async run(): Promise<PerformanceReport>
startMonitoring() ⭐️ NEW

启动持续监控模式,持续监听所有性能指标的更新。

startMonitoring(): void
stopMonitoring() ⭐️ NEW

停止持续监控,清理所有监听器和定时器。

stopMonitoring(): void
getCurrentMetrics() ⭐️ NEW

获取当前的性能指标快照。

getCurrentMetrics(): PerformanceMetrics | null

返回值: 当前性能指标对象,如果未启动监控则返回 null

generateCurrentReport() ⭐️ NEW

基于当前指标生成完整的性能报告。

generateCurrentReport(): PerformanceReport | null

返回值: 完整的性能报告对象,包含 metrics、score、optimizations,如果未启动监控则返回 null

getDeviceInfo() (静态)

获取当前设备信息。

static getDeviceInfo(): DeviceInfo
generateReport() (静态)

手动生成指定格式的报告。

static generateReport(
  report: PerformanceReport,
  format?: 'console' | 'json' | 'html'
): string | void

PerformanceReport

性能报告对象结构:

interface PerformanceReport {
  timestamp: number;              // 报告生成时间戳
  device: DeviceInfo;             // 设备信息
  metrics: PerformanceMetrics;    // 性能指标
  score: {                        // 性能评分
    overall: number;              // 总分 (0-100)
    fcp: PerformanceLevel;
    lcp: PerformanceLevel;
    fid: PerformanceLevel;
    cls: PerformanceLevel;
  };
  optimizations: Optimization[];  // 优化建议列表
}

🔧 开发

# 安装依赖
npm install

# 开发模式
npm run dev

# 构建
npm run build

# 测试
npm test

📝 注意事项

监控模式选择

  • 持续监控模式 ⭐️ 推荐

    • ✅ 能捕获所有性能指标(包括需要用户交互的 FID、INP)
    • ✅ 实时更新,数据更准确
    • ✅ 适合生产环境长期监控
    • ⚠️ 需要手动调用 stopMonitoring() 清理资源
  • 一次性监控模式

    • ✅ 使用简单,无需清理
    • ⚠️ 10秒超时,可能错过某些指标
    • ⚠️ 仅适合快速性能检测

其他注意事项

  1. 资源清理: 使用持续监控时,务必在页面卸载前调用 stopMonitoring() 避免内存泄漏。

  2. 采样率: 在生产环境中,可以设置采样率来减少性能开销和数据量。

  3. 浏览器兼容性: 依赖 web-vitals 库,支持所有现代浏览器。某些指标在旧浏览器中可能不可用。

  4. 内存信息: performance.memory 仅在 Chrome/Edge 中可用。

  5. 报告上传: 建议使用 onReport 回调将报告发送到后端分析服务。页面卸载时使用 navigator.sendBeacon() 确保数据上报成功。

  6. 指标显示: 未收集到的指标会显示为 N/A,这是正常现象(如 FID 需要用户交互才能触发)。

🆕 升级指南

从 1.0.x 升级到 1.1.0

v1.1.0 引入了持续监控模式,同时保持了向后兼容性。

新功能:

  • ✅ 持续监控 API: startMonitoring(), stopMonitoring()
  • ✅ 实时指标获取: getCurrentMetrics(), generateCurrentReport()
  • ✅ 新配置项: reportInterval, onMetricsUpdate

兼容性:

  • ✅ 所有旧代码无需修改,可直接升级
  • ✅ 原有的 run() 方法仍然可用

推荐迁移:

// 旧方式(仍然可用)
const monitor = new WebPerformanceMonitor();
await monitor.run();

// 新方式(推荐)- 更准确的数据
const monitor = new WebPerformanceMonitor();
monitor.startMonitoring();
// ... 页面卸载时
monitor.stopMonitoring();

查看完整升级说明: CHANGELOG.md

🤝 贡献

欢迎提交 Issue 和 Pull Request!

📄 License

MIT

🔗 相关资源