web-performance-optimization by davila7/claude-code-templates
npx skills add https://github.com/davila7/claude-code-templates --skill web-performance-optimization帮助开发者优化网站和Web应用程序性能,以提升用户体验、SEO排名和转化率。本技能提供系统性的方法来测量、分析和改进加载速度、运行时性能以及核心Web指标。
我将帮助您建立基准指标:
分析性能问题:
专注于高影响力的改进:
应用性能改进:
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
测量变更的影响:
## 性能审计结果
### 当前指标(优化前)
- **LCP (最大内容绘制):** 4.2s ❌ (应 < 2.5s)
- **FID (首次输入延迟):** 180ms ❌ (应 < 100ms)
- **CLS (累积布局偏移):** 0.25 ❌ (应 < 0.1)
- **Lighthouse 分数:** 62/100
### 已识别的问题
1. **LCP 问题:** 主图(2.5MB)加载缓慢
2. **FID 问题:** 大型JavaScript包(850KB)阻塞主线程
3. **CLS 问题:** 未指定尺寸的图片导致布局偏移
### 优化计划
#### 修复 LCP (最大内容绘制)
**问题:** 主图为2.5MB且加载缓慢
**解决方案:**
\`\`\`html
<!-- 之前: 未优化的图片 -->
<img src="/hero.jpg" alt="Hero">
<!-- 之后: 使用现代格式优化 -->
<picture>
<source srcset="/hero.avif" type="image/avif">
<source srcset="/hero.webp" type="image/webp">
<img
src="/hero.jpg"
alt="Hero"
width="1200"
height="600"
loading="eager"
fetchpriority="high"
>
</picture>
\`\`\`
**额外优化:**
- 将图片压缩至 < 200KB
- 使用CDN加速交付
- 预加载主图: `<link rel="preload" as="image" href="/hero.avif">`
#### 修复 FID (首次输入延迟)
**问题:** 850KB的JavaScript包阻塞主线程
**解决方案:**
1. **代码分割:**
\`\`\`javascript
// 之前: 所有内容在一个包中
import { HeavyComponent } from './HeavyComponent';
import { Analytics } from './analytics';
import { ChatWidget } from './chat';
// 之后: 懒加载非关键代码
const HeavyComponent = lazy(() => import('./HeavyComponent'));
const ChatWidget = lazy(() => import('./chat'));
// 页面可交互后加载分析脚本
if (typeof window !== 'undefined') {
window.addEventListener('load', () => {
import('./analytics').then(({ Analytics }) => {
Analytics.init();
});
});
}
\`\`\`
2. **移除未使用的依赖:**
\`\`\`bash
# 分析包
npx webpack-bundle-analyzer
# 移除未使用的包
npm uninstall moment # 使用 date-fns 替代(更小)
npm install date-fns
\`\`\`
3. **延迟非关键脚本:**
\`\`\`html
<!-- 之前: 阻塞渲染 -->
<script src="/analytics.js"></script>
<!-- 之后: 延迟加载 -->
<script src="/analytics.js" defer></script>
\`\`\`
#### 修复 CLS (累积布局偏移)
**问题:** 未指定尺寸的图片导致布局偏移
**解决方案:**
\`\`\`html
<!-- 之前: 无尺寸 -->
<img src="/product.jpg" alt="Product">
<!-- 之后: 指定尺寸 -->
<img
src="/product.jpg"
alt="Product"
width="400"
height="300"
style="aspect-ratio: 4/3;"
>
\`\`\`
**对于动态内容:**
\`\`\`css
/* 为稍后加载的内容预留空间 */
.skeleton-loader {
min-height: 200px;
background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
background-size: 200% 100%;
animation: loading 1.5s infinite;
}
@keyframes loading {
0% { background-position: 200% 0; }
100% { background-position: -200% 0; }
}
\`\`\`
### 优化后的结果
- **LCP:** 1.8s ✅ (提升 57%)
- **FID:** 45ms ✅ (提升 75%)
- **CLS:** 0.05 ✅ (提升 80%)
- **Lighthouse 分数:** 94/100 ✅
## 包大小优化
### 当前状态
- **总包大小:** 850KB (gzipped: 280KB)
- **主包:** 650KB
- **供应商包:** 200KB
- **加载时间 (3G):** 8.2s
### 分析
\`\`\`bash
# 分析包构成
npx webpack-bundle-analyzer dist/stats.json
\`\`\`
**发现:**
1. Moment.js: 67KB (可用 date-fns 替代: 12KB)
2. Lodash: 72KB (使用整个库,但仅需5个函数)
3. 未使用代码: 约150KB的死代码
4. 无代码分割: 所有内容在一个包中
### 优化步骤
#### 1. 替换重型依赖
\`\`\`bash
# 移除 moment.js (67KB) → 使用 date-fns (12KB)
npm uninstall moment
npm install date-fns
# 之前
import moment from 'moment';
const formatted = moment(date).format('YYYY-MM-DD');
# 之后
import { format } from 'date-fns';
const formatted = format(date, 'yyyy-MM-dd');
\`\`\`
**节省:** 55KB
#### 2. 选择性使用 Lodash
\`\`\`javascript
// 之前: 导入整个库 (72KB)
import _ from 'lodash';
const unique = _.uniq(array);
// 之后: 仅导入所需部分 (5KB)
import uniq from 'lodash/uniq';
const unique = uniq(array);
// 或使用原生方法
const unique = [...new Set(array)];
\`\`\`
**节省:** 67KB
#### 3. 实施代码分割
\`\`\`javascript
// Next.js 示例
import dynamic from 'next/dynamic';
// 懒加载重型组件
const Chart = dynamic(() => import('./Chart'), {
loading: () => <div>Loading chart...</div>,
ssr: false
});
const AdminPanel = dynamic(() => import('./AdminPanel'), {
loading: () => <div>Loading...</div>
});
// 基于路由的代码分割 (Next.js 中自动实现)
// pages/admin.js - 仅在访问 /admin 时加载
// pages/dashboard.js - 仅在访问 /dashboard 时加载
\`\`\`
#### 4. 移除死代码
\`\`\`javascript
// 在 webpack.config.js 中启用 tree shaking
module.exports = {
mode: 'production',
optimization: {
usedExports: true,
sideEffects: false
}
};
// 在 package.json 中
{
"sideEffects": false
}
\`\`\`
#### 5. 优化第三方脚本
\`\`\`html
<!-- 之前: 立即加载 -->
<script src="https://analytics.com/script.js"></script>
<!-- 之后: 页面可交互后加载 -->
<script>
window.addEventListener('load', () => {
const script = document.createElement('script');
script.src = 'https://analytics.com/script.js';
script.async = true;
document.body.appendChild(script);
});
</script>
\`\`\`
### 结果
- **总包大小:** 380KB ✅ (减少 55%)
- **主包:** 180KB ✅
- **供应商包:** 80KB ✅
- **加载时间 (3G):** 3.1s ✅ (提升 62%)
## 图片优化
### 当前问题
- 15张图片总计12MB
- 未使用现代格式(WebP、AVIF)
- 无响应式图片
- 无懒加载
### 优化策略
#### 1. 转换为现代格式
\`\`\`bash
# 安装图片优化工具
npm install sharp
# 转换脚本 (optimize-images.js)
const sharp = require('sharp');
const fs = require('fs');
const path = require('path');
async function optimizeImage(inputPath, outputDir) {
const filename = path.basename(inputPath, path.extname(inputPath));
// 生成 WebP
await sharp(inputPath)
.webp({ quality: 80 })
.toFile(path.join(outputDir, \`\${filename}.webp\`));
// 生成 AVIF (最佳压缩)
await sharp(inputPath)
.avif({ quality: 70 })
.toFile(path.join(outputDir, \`\${filename}.avif\`));
// 生成优化的 JPEG 回退版本
await sharp(inputPath)
.jpeg({ quality: 80, progressive: true })
.toFile(path.join(outputDir, \`\${filename}.jpg\`));
}
// 处理所有图片
const images = fs.readdirSync('./images');
images.forEach(img => {
optimizeImage(\`./images/\${img}\`, './images/optimized');
});
\`\`\`
#### 2. 实施响应式图片
\`\`\`html
<!-- 使用现代格式的响应式图片 -->
<picture>
<!-- AVIF 格式 (支持该格式的浏览器,最佳压缩) -->
<source
srcset="
/images/hero-400.avif 400w,
/images/hero-800.avif 800w,
/images/hero-1200.avif 1200w
"
type="image/avif"
sizes="(max-width: 768px) 100vw, 50vw"
>
<!-- WebP 格式 (支持该格式的浏览器) -->
<source
srcset="
/images/hero-400.webp 400w,
/images/hero-800.webp 800w,
/images/hero-1200.webp 1200w
"
type="image/webp"
sizes="(max-width: 768px) 100vw, 50vw"
>
<!-- JPEG 回退 -->
<img
src="/images/hero-800.jpg"
srcset="
/images/hero-400.jpg 400w,
/images/hero-800.jpg 800w,
/images/hero-1200.jpg 1200w
"
sizes="(max-width: 768px) 100vw, 50vw"
alt="Hero image"
width="1200"
height="600"
loading="lazy"
>
</picture>
\`\`\`
#### 3. 懒加载
\`\`\`html
<!-- 原生懒加载 -->
<img
src="/image.jpg"
alt="Description"
loading="lazy"
width="800"
height="600"
>
<!-- 首屏图片使用急切加载 -->
<img
src="/hero.jpg"
alt="Hero"
loading="eager"
fetchpriority="high"
>
\`\`\`
#### 4. Next.js Image 组件
\`\`\`javascript
import Image from 'next/image';
// 自动优化
<Image
src="/hero.jpg"
alt="Hero"
width={1200}
height={600}
priority // 用于首屏图片
quality={80}
/>
// 懒加载
<Image
src="/product.jpg"
alt="Product"
width={400}
height={300}
loading="lazy"
/>
\`\`\`
### 结果
| 指标 | 之前 | 之后 | 提升 |
|--------|--------|-------|-------------|
| 总图片大小 | 12MB | 1.8MB | 减少 85% |
| LCP | 4.5s | 1.6s | 加快 64% |
| 页面加载 (3G) | 18s | 4.2s | 加快 77% |
<link rel="preload"> 预加载关键资源症状: 桌面端Lighthouse分数良好,移动端较差 解决方案:
在真实移动设备上测试
使用Chrome DevTools移动端节流
针对3G/4G网络进行优化
减少JavaScript执行时间
lighthouse https://yoursite.com --throttling.cpuSlowdownMultiplier=4
症状: 可交互时间长(TTI),FID高 解决方案:
使用 webpack-bundle-analyzer 分析包
移除未使用的依赖
实施代码分割
懒加载非关键代码
npx webpack-bundle-analyzer dist/stats.json
症状: CLS分数高,内容跳动 解决方案:
始终指定宽度和高度
使用 aspect-ratio CSS属性
使用骨架屏预留空间
img { aspect-ratio: 16 / 9; width: 100%; height: auto; }
症状: TTFB(首字节时间)高 解决方案:
实施服务器端缓存
使用CDN提供静态资源
优化数据库查询
考虑静态站点生成(SSG)
// Next.js: 静态生成 export async function getStaticProps() { const data = await fetchData(); return { props: { data }, revalidate: 60 // 每60秒重新生成 }; }
@react-best-practices - React性能模式@frontend-dev-guidelines - 前端开发标准@systematic-debugging - 调试性能问题@senior-architect - 性能架构专业提示: 首先专注于核心Web指标(LCP、FID、CLS)——它们对用户体验和SEO排名影响最大!
每周安装数
202
仓库
GitHub 星标数
22.6K
首次出现
Jan 25, 2026
安全审计
安装于
opencode169
gemini-cli161
codex157
cursor154
claude-code153
github-copilot150
Help developers optimize website and web application performance to improve user experience, SEO rankings, and conversion rates. This skill provides systematic approaches to measure, analyze, and improve loading speed, runtime performance, and Core Web Vitals metrics.
I'll help you establish baseline metrics:
Analyze performance problems:
Focus on high-impact improvements:
Apply performance improvements:
Measure impact of changes:
## Performance Audit Results
### Current Metrics (Before Optimization)
- **LCP (Largest Contentful Paint):** 4.2s ❌ (should be < 2.5s)
- **FID (First Input Delay):** 180ms ❌ (should be < 100ms)
- **CLS (Cumulative Layout Shift):** 0.25 ❌ (should be < 0.1)
- **Lighthouse Score:** 62/100
### Issues Identified
1. **LCP Issue:** Hero image (2.5MB) loads slowly
2. **FID Issue:** Large JavaScript bundle (850KB) blocks main thread
3. **CLS Issue:** Images without dimensions cause layout shifts
### Optimization Plan
#### Fix LCP (Largest Contentful Paint)
**Problem:** Hero image is 2.5MB and loads slowly
**Solutions:**
\`\`\`html
<!-- Before: Unoptimized image -->
<img src="/hero.jpg" alt="Hero">
<!-- After: Optimized with modern formats -->
<picture>
<source srcset="/hero.avif" type="image/avif">
<source srcset="/hero.webp" type="image/webp">
<img
src="/hero.jpg"
alt="Hero"
width="1200"
height="600"
loading="eager"
fetchpriority="high"
>
</picture>
\`\`\`
**Additional optimizations:**
- Compress image to < 200KB
- Use CDN for faster delivery
- Preload hero image: `<link rel="preload" as="image" href="/hero.avif">`
#### Fix FID (First Input Delay)
**Problem:** 850KB JavaScript bundle blocks main thread
**Solutions:**
1. **Code Splitting:**
\`\`\`javascript
// Before: Everything in one bundle
import { HeavyComponent } from './HeavyComponent';
import { Analytics } from './analytics';
import { ChatWidget } from './chat';
// After: Lazy load non-critical code
const HeavyComponent = lazy(() => import('./HeavyComponent'));
const ChatWidget = lazy(() => import('./chat'));
// Load analytics after page interactive
if (typeof window !== 'undefined') {
window.addEventListener('load', () => {
import('./analytics').then(({ Analytics }) => {
Analytics.init();
});
});
}
\`\`\`
2. **Remove Unused Dependencies:**
\`\`\`bash
# Analyze bundle
npx webpack-bundle-analyzer
# Remove unused packages
npm uninstall moment # Use date-fns instead (smaller)
npm install date-fns
\`\`\`
3. **Defer Non-Critical Scripts:**
\`\`\`html
<!-- Before: Blocks rendering -->
<script src="/analytics.js"></script>
<!-- After: Deferred -->
<script src="/analytics.js" defer></script>
\`\`\`
#### Fix CLS (Cumulative Layout Shift)
**Problem:** Images without dimensions cause layout shifts
**Solutions:**
\`\`\`html
<!-- Before: No dimensions -->
<img src="/product.jpg" alt="Product">
<!-- After: With dimensions -->
<img
src="/product.jpg"
alt="Product"
width="400"
height="300"
style="aspect-ratio: 4/3;"
>
\`\`\`
**For dynamic content:**
\`\`\`css
/* Reserve space for content that loads later */
.skeleton-loader {
min-height: 200px;
background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
background-size: 200% 100%;
animation: loading 1.5s infinite;
}
@keyframes loading {
0% { background-position: 200% 0; }
100% { background-position: -200% 0; }
}
\`\`\`
### Results After Optimization
- **LCP:** 1.8s ✅ (improved by 57%)
- **FID:** 45ms ✅ (improved by 75%)
- **CLS:** 0.05 ✅ (improved by 80%)
- **Lighthouse Score:** 94/100 ✅
## Bundle Size Optimization
### Current State
- **Total Bundle:** 850KB (gzipped: 280KB)
- **Main Bundle:** 650KB
- **Vendor Bundle:** 200KB
- **Load Time (3G):** 8.2s
### Analysis
\`\`\`bash
# Analyze bundle composition
npx webpack-bundle-analyzer dist/stats.json
\`\`\`
**Findings:**
1. Moment.js: 67KB (can replace with date-fns: 12KB)
2. Lodash: 72KB (using entire library, only need 5 functions)
3. Unused code: ~150KB of dead code
4. No code splitting: Everything in one bundle
### Optimization Steps
#### 1. Replace Heavy Dependencies
\`\`\`bash
# Remove moment.js (67KB) → Use date-fns (12KB)
npm uninstall moment
npm install date-fns
# Before
import moment from 'moment';
const formatted = moment(date).format('YYYY-MM-DD');
# After
import { format } from 'date-fns';
const formatted = format(date, 'yyyy-MM-dd');
\`\`\`
**Savings:** 55KB
#### 2. Use Lodash Selectively
\`\`\`javascript
// Before: Import entire library (72KB)
import _ from 'lodash';
const unique = _.uniq(array);
// After: Import only what you need (5KB)
import uniq from 'lodash/uniq';
const unique = uniq(array);
// Or use native methods
const unique = [...new Set(array)];
\`\`\`
**Savings:** 67KB
#### 3. Implement Code Splitting
\`\`\`javascript
// Next.js example
import dynamic from 'next/dynamic';
// Lazy load heavy components
const Chart = dynamic(() => import('./Chart'), {
loading: () => <div>Loading chart...</div>,
ssr: false
});
const AdminPanel = dynamic(() => import('./AdminPanel'), {
loading: () => <div>Loading...</div>
});
// Route-based code splitting (automatic in Next.js)
// pages/admin.js - Only loaded when visiting /admin
// pages/dashboard.js - Only loaded when visiting /dashboard
\`\`\`
#### 4. Remove Dead Code
\`\`\`javascript
// Enable tree shaking in webpack.config.js
module.exports = {
mode: 'production',
optimization: {
usedExports: true,
sideEffects: false
}
};
// In package.json
{
"sideEffects": false
}
\`\`\`
#### 5. Optimize Third-Party Scripts
\`\`\`html
<!-- Before: Loads immediately -->
<script src="https://analytics.com/script.js"></script>
<!-- After: Load after page interactive -->
<script>
window.addEventListener('load', () => {
const script = document.createElement('script');
script.src = 'https://analytics.com/script.js';
script.async = true;
document.body.appendChild(script);
});
</script>
\`\`\`
### Results
- **Total Bundle:** 380KB ✅ (reduced by 55%)
- **Main Bundle:** 180KB ✅
- **Vendor Bundle:** 80KB ✅
- **Load Time (3G):** 3.1s ✅ (improved by 62%)
## Image Optimization
### Current Issues
- 15 images totaling 12MB
- No modern formats (WebP, AVIF)
- No responsive images
- No lazy loading
### Optimization Strategy
#### 1. Convert to Modern Formats
\`\`\`bash
# Install image optimization tools
npm install sharp
# Conversion script (optimize-images.js)
const sharp = require('sharp');
const fs = require('fs');
const path = require('path');
async function optimizeImage(inputPath, outputDir) {
const filename = path.basename(inputPath, path.extname(inputPath));
// Generate WebP
await sharp(inputPath)
.webp({ quality: 80 })
.toFile(path.join(outputDir, \`\${filename}.webp\`));
// Generate AVIF (best compression)
await sharp(inputPath)
.avif({ quality: 70 })
.toFile(path.join(outputDir, \`\${filename}.avif\`));
// Generate optimized JPEG fallback
await sharp(inputPath)
.jpeg({ quality: 80, progressive: true })
.toFile(path.join(outputDir, \`\${filename}.jpg\`));
}
// Process all images
const images = fs.readdirSync('./images');
images.forEach(img => {
optimizeImage(\`./images/\${img}\`, './images/optimized');
});
\`\`\`
#### 2. Implement Responsive Images
\`\`\`html
<!-- Responsive images with modern formats -->
<picture>
<!-- AVIF for browsers that support it (best compression) -->
<source
srcset="
/images/hero-400.avif 400w,
/images/hero-800.avif 800w,
/images/hero-1200.avif 1200w
"
type="image/avif"
sizes="(max-width: 768px) 100vw, 50vw"
>
<!-- WebP for browsers that support it -->
<source
srcset="
/images/hero-400.webp 400w,
/images/hero-800.webp 800w,
/images/hero-1200.webp 1200w
"
type="image/webp"
sizes="(max-width: 768px) 100vw, 50vw"
>
<!-- JPEG fallback -->
<img
src="/images/hero-800.jpg"
srcset="
/images/hero-400.jpg 400w,
/images/hero-800.jpg 800w,
/images/hero-1200.jpg 1200w
"
sizes="(max-width: 768px) 100vw, 50vw"
alt="Hero image"
width="1200"
height="600"
loading="lazy"
>
</picture>
\`\`\`
#### 3. Lazy Loading
\`\`\`html
<!-- Native lazy loading -->
<img
src="/image.jpg"
alt="Description"
loading="lazy"
width="800"
height="600"
>
<!-- Eager loading for above-the-fold images -->
<img
src="/hero.jpg"
alt="Hero"
loading="eager"
fetchpriority="high"
>
\`\`\`
#### 4. Next.js Image Component
\`\`\`javascript
import Image from 'next/image';
// Automatic optimization
<Image
src="/hero.jpg"
alt="Hero"
width={1200}
height={600}
priority // For above-the-fold images
quality={80}
/>
// Lazy loaded
<Image
src="/product.jpg"
alt="Product"
width={400}
height={300}
loading="lazy"
/>
\`\`\`
### Results
| Metric | Before | After | Improvement |
|--------|--------|-------|-------------|
| Total Image Size | 12MB | 1.8MB | 85% reduction |
| LCP | 4.5s | 1.6s | 64% faster |
| Page Load (3G) | 18s | 4.2s | 77% faster |
<link rel="preload"> for critical assetsSymptoms: Good Lighthouse score on desktop, poor on mobile Solution:
Test on real mobile devices
Use Chrome DevTools mobile throttling
Optimize for 3G/4G networks
Reduce JavaScript execution time
lighthouse https://yoursite.com --throttling.cpuSlowdownMultiplier=4
Symptoms: Long Time to Interactive (TTI), high FID Solution:
Analyze bundle with webpack-bundle-analyzer
Remove unused dependencies
Implement code splitting
Lazy load non-critical code
npx webpack-bundle-analyzer dist/stats.json
Symptoms: High CLS score, content jumping Solution:
Always specify width and height
Use aspect-ratio CSS property
Reserve space with skeleton loaders
img { aspect-ratio: 16 / 9; width: 100%; height: auto; }
Symptoms: High TTFB (Time to First Byte) Solution:
Implement server-side caching
Use CDN for static assets
Optimize database queries
Consider static site generation (SSG)
// Next.js: Static generation export async function getStaticProps() { const data = await fetchData(); return { props: { data }, revalidate: 60 // Regenerate every 60 seconds }; }
@react-best-practices - React performance patterns@frontend-dev-guidelines - Frontend development standards@systematic-debugging - Debug performance issues@senior-architect - Architecture for performancePro Tip: Focus on Core Web Vitals (LCP, FID, CLS) first - they have the biggest impact on user experience and SEO rankings!
Weekly Installs
202
Repository
GitHub Stars
22.6K
First Seen
Jan 25, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode169
gemini-cli161
codex157
cursor154
claude-code153
github-copilot150
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
106,200 周安装
TOON 格式:面向令牌的对象表示法,专为LLM优化的紧凑数据编码
227 周安装
Grimmory 自托管图书馆管理器:支持 EPUB/PDF/MOBI/CBZ 的 Docker 部署方案
227 周安装
Anthropic Claude技能开发最佳实践:编写高效AI技能指南与命名规范
227 周安装
Git Commit 自动化工具:规范提交消息,提升代码管理效率
227 周安装
Pirate Skill - 谷歌Gemini CLI的海盗风格AI助手 | 命令行AI工具
227 周安装
品牌视觉识别生成器 - 提升品牌一致性与收入23-33%的AI设计指南
227 周安装