What Is Lazy Loading?
Definition:
On this page
What Is Lazy Loading?
1. What Is Lazy Loading?
Definition:
Lazy Loading is a technique that only loads or initializes a resource (image, data, component, module, etc.) when it's actually needed, instead of loading everything up front. This improves performance, reduces page-load time, and saves system resources.
2. Problems Lazy Loading Solves
- Faster page loads: Pages render faster since not all resources have to be downloaded immediately.
- Bandwidth savings: Only loads what the user actually needs to see or use.
- Reduced server load: Fewer simultaneous requests and less data to process, especially for large applications.
- Better user experience: Users see the main content sooner, while secondary parts load as needed.
3. Common Types of Lazy Loading
a. Image Lazy Loading
Only loads an image once it appears in the viewport.
Example:
<img src="thumbnail.jpg" data-src="large-image.jpg" loading="lazy" alt="Large image" />
Or use a library like lazysizes or react-lazyload.
b. Component/Module Lazy Loading (React/JS)
Only loads a component or module once the user navigates to that part of the app (code splitting).
Example with React:
import React, { Suspense, lazy } from 'react';
// Load the component on demand
const UserProfile = lazy(() => import('./UserProfile'));
function App() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<UserProfile />
</Suspense>
</div>
);
}
Or with React Router:
import { lazy } from 'react';
const AdminPage = lazy(() => import('./AdminPage'));
<Route path="/admin" element={<AdminPage />} />
c. Lazy Loading with Intersection Observer
The Intersection Observer API is a Web API that lets you detect when an element enters the viewport, letting you trigger actions like lazy-loading images, animations, or API calls.
Example:
const LazyProductList = () => {
const observer = useRef<IntersectionObserver | null>(null);
const lastProductRef = useRef<HTMLLIElement | null>(null);
const fetchProducts = async () => {
...
};
useEffect(() => {
const callback = (entries: IntersectionObserverEntry[]) => {
if (entries[0].isIntersecting) {
fetchProducts();
}
};
observer.current = new IntersectionObserver(callback, {threshold: 1.0});
const currentRef = lastProductRef.current;
if (currentRef) {
observer.current.observe(currentRef);
}
return () => {
if (currentRef && observer.current) {
observer.current.unobserve(currentRef);
}
};
}, []);
return (
<>
<ul>
{products.map((product, index) => {
const isLastProduct = index === products.length - 1;
return (
<li key={index} ref={isLastProduct ? lastProductRef : null}>
{product.name}
</li>
);
})}
</ul>
</>
);
};
export default LazyProductList;
}
4. Things to Watch Out for When Using Lazy Loading
- Make sure you have a fallback/loading UI so users don't see a blank page while resources are still loading.
- For images, use the
loading="lazy"attribute and check browser compatibility. - For components, use React's
Suspenseto manage the loading state. - Watch out for SEO if you're lazy-loading images or important content (consider preloading or using SSR if needed).
- Test real-world performance and avoid lazy-loading too aggressively, which can lead to a stream of small, repeated requests.
5. Benefits and Limitations
| Benefits | Limitations |
|---|---|
| Faster page loads | More complexity in the code |
| Saves bandwidth | Can affect SEO |
| Improves UX | Requires handling loading/error UI |
| Reduces server load | Needs thorough testing |
6. Summary
Lazy Loading is an extremely important optimization technique for modern web apps, especially large applications or ones with lots of images/data. Apply it wisely to improve your app's UX and performance!
