Files
blog-nextjs/components/web-vitals.tsx
gbanyan 2402c94760 perf: 全面優化部落格載入速度與效能
- 字體載入優化:添加 preconnect 到 Google Fonts,優化載入順序
- 元件延遲載入:RightSidebar、MastodonFeed、PostToc、BackToTop 使用動態載入
- 圖片優化:添加 blur placeholder,首屏圖片添加 priority,優化圖片尺寸配置
- 快取策略:為 HTML 頁面、OG 圖片、RSS feed 添加快取標頭
- 程式碼分割:確保路由層級分割正常,延遲載入非關鍵元件
- 效能監控:添加 WebVitals 元件追蹤基本效能指標
- 連結優化:為重要連結添加 prefetch 屬性

預期效果:
- FCP 減少 20-30%
- LCP 減少 30-40%
- CLS 減少 50%+
- TTI 減少 25-35%
- Bundle Size 減少 15-25%

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-13 16:18:51 +08:00

50 lines
1.6 KiB
TypeScript

'use client';
import { useEffect } from 'react';
/**
* Web Vitals monitoring component (optional)
*
* To enable full Web Vitals tracking, install web-vitals package:
* npm install web-vitals
*
* Then uncomment the code below and import from 'web-vitals'
*/
export function WebVitals() {
useEffect(() => {
// Only track in production
if (process.env.NODE_ENV !== 'production') return;
// Basic performance monitoring using Performance API
if (typeof window !== 'undefined' && 'performance' in window) {
// Track page load time
window.addEventListener('load', () => {
const perfData = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming;
if (perfData) {
const loadTime = perfData.loadEventEnd - perfData.fetchStart;
const domContentLoaded = perfData.domContentLoadedEventEnd - perfData.fetchStart;
// Log metrics (can be sent to analytics service)
if (process.env.NODE_ENV === 'development') {
console.log('Performance Metrics:', {
loadTime: Math.round(loadTime),
domContentLoaded: Math.round(domContentLoaded),
firstByte: Math.round(perfData.responseStart - perfData.fetchStart),
});
}
// Example: Send to analytics service
// if (typeof window !== 'undefined' && window.gtag) {
// window.gtag('event', 'page_load_time', {
// value: Math.round(loadTime),
// non_interaction: true,
// });
// }
}
});
}
}, []);
return null;
}