欢迎来到程序员中文网!

首页 Linux Mysql C++ Python PHP JavaScript 资源下载 动态 开源推荐
我要投稿 投诉建议

前端性能优化:懒加载与代码分割

时间:2026年08月12日 04:50:02 浏览:1

图片懒加载


<img loading="lazy" src="placeholder.jpg" data-src="real.jpg" alt="">

或使用 Intersection Observer:


const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
});
document.querySelectorAll('img[data-src]').forEach(img => observer.observe(img));

路由代码分割(React)


import React, { lazy, Suspense } from 'react';

const Home = lazy(() => import('./Home'));
const About = lazy(() => import('./About'));

function App() {
return (
<Suspense fallback={<div>加载中...</div>}>
<Home />
</Suspense>
);
}

按需加载(动态 import)


button.addEventListener('click', async () => {
const module = await import('./heavy-module');
module.default();
});

其他策略



  • 使用 CDN 加速静态资源

  • 启用 gzip 压缩

  • 减少 HTTP 请求(合并文件)

  • 使用 preloadprefetch 预加载关键资源


性能优化是前端开发的重要一环,能显著提升用户体验。