前端页面加载时间缩短实战指南
图片懒加载优化
使用 Intersection Observer API 实现图片懒加载,避免首屏渲染阻塞。
const imageObserver = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
img.classList.remove('lazy');
observer.unobserve(img);
}
});
});
document.querySelectorAll('img[data-src]').forEach(img => {
imageObserver.observe(img);
});
资源预加载策略
在关键资源前添加预加载标签,提升首屏渲染速度。
<link rel="preload" href="/critical.css" as="style">
<link rel="preload" href="/hero-image.jpg" as="image">
<link rel="prefetch" href="/next-page.js">
代码分割与动态导入
使用 Webpack 的动态导入功能,实现按需加载。
// 原始代码
import { heavyFunction } from './heavy-module.js';
// 优化后
const loadModule = async () => {
const { heavyFunction } = await import('./heavy-module.js');
return heavyFunction();
};
字体优化技巧
使用 font-display: swap 确保字体加载时不阻塞页面渲染。
@font-face {
font-family: 'CustomFont';
src: url('/font.woff2') format('woff2');
font-display: swap;
}
CDN 配置优化
配置合适的缓存策略,减少重复请求。
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
通过以上策略组合使用,可将页面加载时间平均缩短 40-60%。

讨论