video-flow-b/docs/页面加载优化方案.md
2025-10-27 15:48:42 +08:00

341 lines
8.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# ⚡ video-flow-b 性能优化快速实施指南
> **紧急修复清单** - 可在1-2天内完成立即提升50%+性能
## 🚨 立即修复30分钟内
### 1. 启用图片优化
**影响**: 减少50-70%图片加载时间
```javascript
// next.config.js - 找到这行并修改
const nextConfig = {
images: {
unoptimized: false, // ✅ 改为 false
formats: ['image/webp', 'image/avif'],
domains: ['cdn.qikongjian.com'],
},
};
```
### 2. 修复JSON解析性能灾难
**影响**: 消除每秒数百次异常提升渲染性能70%
```typescript
// 找到 parseTaskResult 函数并替换为:
function parseTaskResult(taskResult: any) {
if (!taskResult) return null;
if (typeof taskResult === 'string') {
const trimmed = taskResult.trim();
// 快速检查,避免异常
if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) {
return { raw_text: trimmed };
}
try {
return JSON.parse(taskResult);
} catch {
// 静默处理,避免大量日志
return { raw_text: trimmed, parse_error: true };
}
}
return taskResult;
}
```
### 3. 减少视频预加载
**影响**: 减少200-400MB初始加载
```typescript
// components/pages/home-page2.tsx
// 找到 preloadAllVideos 函数,替换为:
const preloadCriticalVideos = async () => {
// 只预加载首屏关键视频
const criticalVideo = "https://cdn.qikongjian.com/videos/home.mp4";
// 检查网络条件
const connection = (navigator as any).connection;
if (connection?.saveData || connection?.effectiveType === '2g') {
return; // 慢速网络跳过预加载
}
await preloadVideo(criticalVideo);
};
```
## 🔥 快速优化2小时内
### 4. TensorFlow.js 按需加载
**影响**: 减少271MB首屏加载
```typescript
// 创建 hooks/useTensorFlow.ts
import { useState, useCallback } from 'react';
export const useTensorFlow = () => {
const [isLoading, setIsLoading] = useState(false);
const [tfModule, setTfModule] = useState(null);
const loadTensorFlow = useCallback(async () => {
if (tfModule) return tfModule;
setIsLoading(true);
try {
const [tf, cocoSsd] = await Promise.all([
import('@tensorflow/tfjs'),
import('@tensorflow-models/coco-ssd')
]);
const module = { tf, cocoSsd };
setTfModule(module);
return module;
} finally {
setIsLoading(false);
}
}, [tfModule]);
return { loadTensorFlow, isLoading, isLoaded: !!tfModule };
};
```
```typescript
// 更新人物检测组件
export const PersonDetection = ({ videoSrc, onDetection }) => {
const { loadTensorFlow, isLoading } = useTensorFlow();
const [isReady, setIsReady] = useState(false);
if (!isReady) {
return (
<button
onClick={async () => {
await loadTensorFlow();
setIsReady(true);
}}
disabled={isLoading}
>
{isLoading ? 'Loading AI...' : 'Enable AI Detection'}
</button>
);
}
return <PersonDetectionCore videoSrc={videoSrc} onDetection={onDetection} />;
};
```
### 5. API请求超时优化
**影响**: 改善用户体验,减少长时间等待
```typescript
// api/request.ts - 修改超时配置
const request = axios.create({
baseURL: BASE_URL,
timeout: 30000, // ✅ 改为30秒原来是300秒
headers: {
'Content-Type': 'application/json',
},
});
```
### 6. 轮询频率优化
**影响**: 减少服务器负载,提升响应速度
```typescript
// 找到轮询逻辑,修改间隔时间
const getRefreshInterval = () => {
const hasRunningTasks = /* 检查逻辑 */;
if (hasRunningTasks) {
return 15000; // ✅ 改为15秒原来是10秒
} else {
return 60000; // ✅ 改为60秒原来是30秒
}
};
```
## ⚡ 中期优化1天内
### 7. Ant Design 按需导入
**步骤1**: 安装插件
```bash
npm install babel-plugin-import --save-dev
```
**步骤2**: 配置babel
```javascript
// .babelrc
{
"presets": ["next/babel"],
"plugins": [
["import", {
"libraryName": "antd",
"libraryDirectory": "es",
"style": "css"
}]
]
}
```
**步骤3**: 更新导入方式
```typescript
// ❌ 当前方式
import { Button, Modal, Input } from 'antd';
// ✅ 优化方式
import Button from 'antd/es/button';
import Modal from 'antd/es/modal';
import Input from 'antd/es/input';
```
### 8. Three.js 条件加载
**影响**: 减少31MB非必要加载
```typescript
// components/vanta-halo-background.tsx
import { lazy, Suspense } from 'react';
// 检查设备性能
const shouldLoadThreeJS = () => {
const hardwareConcurrency = navigator.hardwareConcurrency || 2;
const deviceMemory = (navigator as any).deviceMemory || 4;
return hardwareConcurrency >= 4 && deviceMemory >= 4;
};
const VantaBackground = lazy(() => {
if (!shouldLoadThreeJS()) {
return import('./StaticBackground'); // 静态背景降级
}
return import('./VantaHaloBackground');
});
export const BackgroundWrapper = () => (
<Suspense fallback={<div className="bg-gradient-to-br from-blue-900 to-purple-900" />}>
<VantaBackground />
</Suspense>
);
```
### 9. 构建配置优化
**影响**: 改善代码分割减少bundle大小
```javascript
// next.config.js - 添加生产环境优化
const nextConfig = {
webpack: (config, { dev, isServer }) => {
// 生产环境也需要优化
if (!dev && !isServer) {
config.optimization.splitChunks = {
chunks: 'all',
cacheGroups: {
// 分离大型第三方库
tensorflow: {
test: /[\\/]node_modules[\\/]@tensorflow/,
name: 'tensorflow',
chunks: 'async',
priority: 30,
},
antd: {
test: /[\\/]node_modules[\\/]antd/,
name: 'antd',
chunks: 'all',
priority: 25,
},
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
priority: 20,
},
},
};
}
return config;
},
// 启用压缩和优化
compress: true,
optimizeFonts: true,
experimental: {
optimizeCss: true,
},
};
```
## 📊 验证优化效果
### 快速测试命令
```bash
# 1. 构建并分析bundle
ANALYZE=true npm run build
# 2. 启动应用
npm start
# 3. 在另一个终端运行Lighthouse
npx lighthouse http://localhost:3000 --output=html --output-path=lighthouse-report.html
# 4. 检查bundle大小
ls -lh .next/static/chunks/ | head -10
```
### 关键指标检查
- **首屏加载时间**: 应该从8-15秒降到4-6秒
- **Bundle大小**: 主要chunk应该从500KB+降到300KB以下
- **Lighthouse性能分数**: 应该从30-50分提升到60-70分
- **控制台错误**: JSON解析错误应该大幅减少
## 🚀 预期效果
实施这些快速修复后,你应该看到:
| 指标 | 优化前 | 优化后 | 提升 |
|------|--------|--------|------|
| **首屏加载** | 8-15秒 | 4-6秒 | **50%** ⬇️ |
| **Bundle大小** | 2-3MB | 1.5-2MB | **30%** ⬇️ |
| **资源加载** | 300-500MB | 100-200MB | **60%** ⬇️ |
| **Lighthouse分数** | 30-50 | 60-70 | **40%** ⬆️ |
## ⚠️ 注意事项
1. **备份代码**: 修改前请确保代码已提交到git
2. **测试功能**: 每个修改后都要测试相关功能是否正常
3. **分步实施**: 建议一个一个修改,避免同时修改太多
4. **监控错误**: 修改后注意观察控制台是否有新的错误
## 🆘 遇到问题?
### 常见问题解决
**Q: 图片优化后显示异常?**
A: 检查图片路径和域名配置确保CDN域名已添加到配置中
**Q: TensorFlow动态加载失败**
A: 检查网络连接,可能需要添加错误处理和重试机制
**Q: Ant Design样式丢失**
A: 确保babel配置正确可能需要重启开发服务器
**Q: 构建失败?**
A: 检查webpack配置语法确保所有依赖都已安装
### 紧急回滚
如果优化后出现严重问题,可以快速回滚:
```bash
# 回滚到上一个提交
git reset --hard HEAD~1
# 或者撤销特定文件的修改
git checkout HEAD -- next.config.js
git checkout HEAD -- components/pages/home-page2.tsx
```
---
**开始优化吧!** 🚀 这些修改可以立即带来显著的性能提升。