mcpField
P
performance-budget-setter

performance-budget-setter

github.com/patricio0312rev测试与质量63216 次安装41 周前更新
代码仓库

关于 performance-budget-setter

performance-budget-setter 是用于制定和执行性能预算的技能,面向维护网站加载速度的开发团队。它涵盖 CI 检查、真实用户与合成监控,以及超出预算后的处理流程。

主要功能

  1. 01定义资源大小与延迟预算
  2. 02在 CI/CD 中自动检查预算
  3. 03规划真实用户与合成监控
  4. 04制定超预算响应流程
  5. 05提供代码、API 与数据库优化建议

适用场景

  1. 01为网站发布设置性能门槛
  2. 02在合并拉取请求前检查资源包大小
  3. 03监控 Core Web Vitals 并处理预算超限

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/patricio0312rev/skills --skill performance-budget-setter

安装后在 Claude Code 中输入/performance-budget-setter确认已加载。

详细介绍

性能预算设置器

设置并执行性能预算,保持快速的用户体验。

性能预算模板

# Performance Budget: E-Commerce Website

## Bundle Size Budget

| Asset Type             | Budget     | Current    | Status |
| ---------------------- | ---------- | ---------- | ------ |
| Initial JS             | 200 KB     | 185 KB     | ✅     |
| Initial CSS            | 50 KB      | 48 KB      | ✅     |
| Vendor JS              | 150 KB     | 145 KB     | ✅     |
| Fonts                  | 100 KB     | 95 KB      | ✅     |
| Images (above fold)    | 300 KB     | 320 KB     | ❌     |
| **Total Initial Load** | **800 KB** | **793 KB** | ✅     |

## API Latency Budget

| Endpoint       | p50    | p95    | p99     |
| -------------- | ------ | ------ | ------- |
| GET /products  | <100ms | <300ms | <500ms  |
| POST /checkout | <200ms | <500ms | <1000ms |
| GET /search    | <150ms | <400ms | <800ms  |

## Database Query Budget

| Query Type       | Budget | Current |
| ---------------- | ------ | ------- |
| Simple reads     | <50ms  | 42ms    |
| Complex joins    | <200ms | 185ms   |
| Aggregations     | <500ms | 450ms   |
| Queries per page | <20    | 18      |

## Core Web Vitals

| Metric                         | Good   | Poor   | Target |
| ------------------------------ | ------ | ------ | ------ |
| LCP (Largest Contentful Paint) | <2.5s  | >4.0s  | <2.0s  |
| FID (First Input Delay)        | <100ms | >300ms | <50ms  |
| CLS (Cumulative Layout Shift)  | <0.1   | >0.25  | <0.05  |

## Page-Specific Budgets

### Homepage

- Time to Interactive: <3s
- Total Blocking Time: <300ms
- Speed Index: <3s

### Product Page

- Time to Interactive: <4s
- Images loaded: <2s
- Reviews section: <1s

### Checkout

- Time to Interactive: <3s
- Payment processing: <2s
- Zero layout shifts

## Third-Party Scripts

| Service     | Budget     | Purpose          |
| ----------- | ---------- | ---------------- |
| Analytics   | 30 KB      | Google Analytics |
| Chat Widget | 50 KB      | Customer support |
| Payment     | 100 KB     | Stripe           |
| **Total**   | **180 KB** |                  |

执行策略

1. CI/CD 集成
# .github/workflows/performance-budget.yml
name: Performance Budget Check

on: [pull_request]

jobs:
  budget-check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2

      - name: Build production bundle
        run: npm run build

      - name: Check bundle size
        run: |
          npx bundlesize

      - name: Lighthouse CI
        run: |
          npm install -g @lhci/cli
          lhci autorun
2. Webpack Bundle Analyzer
// webpack.config.js
const BundleAnalyzerPlugin =
  require("webpack-bundle-analyzer").BundleAnalyzerPlugin;

module.exports = {
  plugins: [
    new BundleAnalyzerPlugin({
      analyzerMode: process.env.ANALYZE ? "server" : "disabled",
    }),
  ],
  performance: {
    hints: "error",
    maxAssetSize: 200000, // 200 KB
    maxEntrypointSize: 400000, // 400 KB
  },
};
3. package.json 配置
{
  "bundlesize": [
    {
      "path": "./dist/js/main.*.js",
      "maxSize": "200 KB"
    },
    {
      "path": "./dist/css/main.*.css",
      "maxSize": "50 KB"
    },
    {
      "path": "./dist/js/vendor.*.js",
      "maxSize": "150 KB"
    }
  ]
}

监控计划

真实用户监控(RUM)
// Track Core Web Vitals
import { getCLS, getFID, getFCP, getLCP, getTTFB } from "web-vitals";

function sendToAnalytics(metric) {
  const body = JSON.stringify(metric);

  if (navigator.sendBeacon) {
    navigator.sendBeacon("/analytics", body);
  } else {
    fetch("/analytics", { body, method: "POST", keepalive: true });
  }
}

getCLS(sendToAnalytics);
getFID(sendToAnalytics);
getLCP(sendToAnalytics);
合成监控
# Lighthouse CI
lhci autorun --config=.lighthouserc.json

# WebPageTest API
curl "https://www.webpagetest.org/runtest.php?url=https://example.com&k=API_KEY"
性能仪表板
**Daily Metrics:**

- Bundle size trend
- API latency percentiles
- Core Web Vitals scores
- Page load times

**Alerts:**

- Bundle size exceeds budget by 10%
- LCP >2.5s for >5% of users
- API p95 >500ms
- Any metric exceeds budget

优化策略

减小 Bundle 体积
// Code splitting
const ProductPage = lazy(() => import("./ProductPage"));

// Tree shaking
import { specific } from "library"; // ✅
import * as library from "library"; // ❌

// Dynamic imports
if (featureFlag) {
  const module = await import("./feature");
}
优化 API 调用
// Parallel requests
const [user, orders] = await Promise.all([fetchUser(id), fetchOrders(id)]);

// Caching
const cachedData = await redis.get(key);
if (cachedData) return cachedData;

// Pagination
const products = await db.products
  .find()
  .limit(20)
  .skip((page - 1) * 20);
优化数据库查询
-- Add indexes
CREATE INDEX idx_orders_user_created ON orders(user_id, created_at);

-- Limit columns
SELECT id, name FROM products; -- ✅
SELECT * FROM products;        -- ❌

-- Use EXPLAIN
EXPLAIN ANALYZE SELECT ...;

预算超限响应

超出预算时
  1. 立即:

    • 阻止 PR 合并
    • 在 Slack 中通知团队
    • 创建工单
  2. 24 小时内:

    • 调查原因
    • 找出优化机会
    • 提出修复方案或增加预算
  3. 决策:

    • 修复代码(优先)
    • 增加预算(需要说明理由)
预算增加申请模板
## Budget Increase Request

**Component:** Main JS bundle
**Current Budget:** 200 KB
**Requested Budget:** 250 KB
**Reason:** Added critical feature X

**Impact Analysis:**

- Load time increase: +0.5s
- User impact: Medium
- Revenue impact: Unknown

**Alternatives Considered:**

1. Code splitting: Reduces to 210 KB (preferred)
2. Remove feature Y: Reduces to 195 KB (rejected)
3. Lazy loading: Complex, 3 weeks effort

**Recommendation:** Implement code splitting

最佳实践

  1. 设定切合实际的预算:基于用户数据
  2. 在 CI 中执行:自动化检查
  3. 持续监控:RUM + 合成监控
  4. 每季度审查:根据需要调整
  5. 优先考虑用户体验:以用户为中心的指标
  6. 记录例外情况:说明增加预算的原因
  7. 庆祝成果:预算低于上限时

输出检查清单

  • 已定义 Bundle 体积预算
  • 已设定 API 延迟目标
  • 已设定数据库查询预算
  • 已设定 Core Web Vitals 目标
  • 已设定特定页面的预算
  • 已配置 CI/CD 执行机制
  • 已创建监控仪表板
  • 已设定告警阈值
  • 已建立超限响应流程
  • 已制定定期审查计划

评论

支持 Markdown