Web 前端性能优化技巧

前言

最近接手了一个老项目,首屏加载时间要8秒。经过两周优化,成功压缩到1.5秒以内。分享实战经验。

一、资源优化

1. 图片优化

<picture>
    <source srcset="image.webp" type="image/webp">
    <img src="image.jpg" alt="图片" loading="lazy">
</picture>

2. JavaScript 优化

// 动态加载
import('./heavy.js').then(m => m.init());

// 代码分割
const LazyComponent = lazy(() => import('./Heavy'));

3. CSS 优化

/* 关键 CSS 内联 */
<style>
    body { margin: 0; font-family: sans-serif; }
</style>

二、网络优化

资源预加载

<link rel="dns-prefetch" href="//cdn.example.com">
<link rel="preconnect" href="https://api.example.com">
<link rel="preload" href="font.woff2" as="font">

三、渲染优化

防抖和节流

const debounce = (fn, delay) => {
    let timer;
    return (...args) => {
        clearTimeout(timer);
        timer = setTimeout(() => fn(...args), delay);
    };
};

四、效果对比

• 首屏加载:8.2s → 1.5s

• 页面大小:5.8MB → 850KB

• 性能评分:32 → 94

← 返回首页

💬 评论 (9)

E
Emma Wilson
2026-01-16
WebP format is fantastic! We reduced our image payload by 40%. Highly recommend everyone switches to it.
吴迪
2026-01-17
WebP 格式真的能节省这么多吗?兼容性怎么样?有没有降级方案?
张伟(博主)
2026-01-17
@吴迪 可以节省30-50%体积。现代浏览器都支持,用 picture 标签做降级就行。AVIF 格式更好,但兼容性还不够。
L
Luis Martinez
2026-01-19
What about lazy loading for videos? Does it work the same way as images?
孙丽
2026-01-20
代码分割这块能详细讲讲吗?我们项目打包后太大了,首次加载特别慢。
张伟(博主)
2026-01-21
@Luis Yes, loading="lazy" works for videos too! @孙丽 可以按路由分割,每个页面单独打包。React 用 lazy + Suspense,后面我会专门写一篇。
K
Kenji Tanaka
2026-01-24
Very helpful article! We implemented these optimizations and our Lighthouse score went from 45 to 92. Thank you!
马云飞
2026-01-28
收藏了,这些技巧都很实用👍 准备应用到公司项目中。
林静
2026-02-02
loading="lazy" 这个属性太好用了!不用自己写 IntersectionObserver 了,原生支持真香。

发表评论