
프론트엔드
Lazy Loading지연 로딩
지연 로딩(Lazy Loading)은 실제로 필요할 때까지 리소스(이미지, 컴포넌트, 데이터) 로딩을 미루는 최적화 기법이다. 초기 로딩 시간 단축, 데이터 절약, 성능 향상을 위해 사용된다.
이미지 지연 로딩
html
<!-- HTML 내장 지연 로딩 (브라우저 네이티브) -->
<img src="photo.webp"
alt="사진"
loading="lazy"
width="400"
height="300">
<!-- 중요 이미지는 eager -->
<img src="hero.webp" loading="eager" fetchpriority="high">Intersection Observer 기반 커스텀 지연 로딩
javascript
// 이미지 지연 로딩 유틸리티
function lazyLoadImages() {
const images = document.querySelectorAll('img[data-src]');
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target as HTMLImageElement;
img.src = img.dataset.src!;
img.removeAttribute('data-src');
observer.unobserve(img);
}
});
}, {
rootMargin: '50px 0px', // 50px 전에 미리 로드
});
images.forEach(img => observer.observe(img));
}React에서 컴포넌트 지연 로딩
typescript
import { lazy, Suspense } from 'react';
// 동적 임포트로 코드 분할
const HeavyChart = lazy(() => import('./HeavyChart'));
const AdminPanel = lazy(() => import('./AdminPanel'));
function App() {
return (
<Suspense fallback={<div>로딩 중...</div>}>
<HeavyChart />
</Suspense>
);
}
// Next.js dynamic
import dynamic from 'next/dynamic';
const Map = dynamic(() => import('./Map'), {
loading: () => <p>지도 로딩 중...</p>,
ssr: false, // 서버에서 렌더링 안 함
});라우트 기반 코드 분할
typescript
// React Router v6
import { lazy, Suspense } from 'react';
import { Routes, Route } from 'react-router-dom';
const Home = lazy(() => import('./pages/Home'));
const About = lazy(() => import('./pages/About'));
const Blog = lazy(() => import('./pages/Blog'));
function App() {
return (
<Suspense fallback={<PageSkeleton />}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/blog" element={<Blog />} />
</Routes>
</Suspense>
);
}관련 개념
- •Intersection Observer API
- •코드 분할
- •Core Web Vitals