Lazy vs Eager Loading: load it now, or when it's needed?
Every app makes the same decision hundreds of times — images, JavaScript bundles, database relationships. Here's what each strategy really does, shown with two simulators you can play with.
01The idea in one sentence
Eager loading fetches a resource up front, before anyone asks for it. Lazy loading waits until the resource is actually needed — when it scrolls into view, when a route is visited, when a property is accessed.
Neither is "better". They trade the same two things against each other: how much work you do at the start versus how long you wait later.
Eager The buffet
Every dish is cooked and laid out before guests arrive. Zero waiting once you're in — but the kitchen did a lot of work, and some dishes go untouched.
Lazy À la carte
Nothing is cooked until you order it. The kitchen never wastes food — but each order takes a moment, and ten separate orders take ten moments.
02Playground: a photo feed
Below is a phone loading a feed of 14 photos over a simulated network. Pick a strategy, then scroll the phone (or press Auto-scroll). Watch the waterfall on the right — each row is one image request.
Try Eager on Slow 3G and watch the first screen: the three photos you can see are fighting 11 photos you can't see for the same connection. That's the hidden cost of eager loading — not just wasted data, but slower content where it matters.
Now try Lazy and scroll fast. You'll catch photos still shimmering as they arrive. That's the hidden cost of lazy loading: the wait moves to the moment of use. Real implementations soften this by starting the download a little before the image reaches the screen (a "root margin") — this simulator starts 120px early.
03Same idea, different place: the database
On the backend the trade-off flips. Fetching from a database has a fixed cost per round-trip, so lazy loading related data in a loop creates the infamous N+1 query problem: 1 query for the list, then 1 more query per row.
Here's a Laravel page listing authors and their post counts. Choose a strategy, set the number of authors, and hit Run.
- -- query log is empty. Press Run.
Drag the slider to 25 and run it lazily. Each individual query is fast; the problem is the count, which grows with your data. A page that's quick with 8 test rows can crawl with 800 production rows. Eager loading with with('posts') keeps it at two queries, forever — one for authors, one WHERE author_id IN (…) for all their posts.
That's why the defaults differ by layer: on the frontend, lazy is usually the safe default (bytes over a slow network are expensive), while for related database records you'll be rendering, eager is usually the safe default (round-trips are expensive).
04How to do it in real code
<!-- Above the fold: eager (the default) — and tell the browser it's important --> <img src="hero.jpg" width="1200" height="600" fetchpriority="high" alt="…"> <!-- Below the fold: let the browser defer it --> <img src="gallery-1.jpg" width="600" height="400" loading="lazy" alt="…"> <iframe src="https://www.youtube.com/embed/…" loading="lazy"></iframe>
Native loading="lazy" needs zero JavaScript. Always set width/height so the layout doesn't jump when the image arrives — and never lazy-load your hero image; it's usually the page's Largest Contentful Paint.
const io = new IntersectionObserver((entries) => { entries.forEach(({ isIntersecting, target }) => { if (!isIntersecting) return; target.src = target.dataset.src; // start the download now io.unobserve(target); }); }, { rootMargin: '200px' }); // begin a little before it's visible document.querySelectorAll('img[data-src]').forEach(img => io.observe(img)); // Lazy-load code, not just images button.addEventListener('click', async () => { const { renderChart } = await import('./charts.js'); renderChart(); });
This is what the simulator above does. Use it when you need custom behaviour (background images, analytics on view). Dynamic import() applies the same idea to JavaScript: the chart library is only downloaded when someone clicks.
import { lazy, Suspense } from 'react'; const Reports = lazy(() => import('./Reports')); // its own bundle chunk export default function App() { return ( <Suspense fallback={<Spinner />}> <Routes> <Route path="/" element={<Home />} /> <Route path="/reports" element={<Reports />} /> </Routes> </Suspense> ); }
React.lazy splits Reports into a separate file that's only fetched when the route is visited. Users who never open Reports never download it. In Next.js, routes are split automatically and next/dynamic does the same for individual components.
// ❌ Lazy in a loop → N+1 queries $authors = Author::all(); foreach ($authors as $author) { echo $author->posts->count(); // a new query every iteration } // ✅ Eager → always 2 queries $authors = Author::with('posts')->get(); // Only need the number? Don't load the rows at all $authors = Author::withCount('posts')->get(); // $author->posts_count // Decided later? "Lazy eager loading" — still one extra query, not N $authors->load('posts'); // AppServiceProvider::boot() — throw on N+1 while developing Model::preventLazyLoading(! app()->isProduction());
Eloquent relationships are lazy by default. preventLazyLoading() turns every accidental N+1 into an exception in development, so you catch it before your users do.
@Entity public class Author { @OneToMany(mappedBy = "author", fetch = FetchType.LAZY) // default for collections private List<Post> posts; } public interface AuthorRepository extends JpaRepository<Author, Long> { // Eager only where this screen needs it @Query("select distinct a from Author a left join fetch a.posts") List<Author> findAllWithPosts(); }
JPA defaults @OneToMany to LAZY and @ManyToOne to EAGER. A good rule: keep mappings lazy and opt into eager per query with join fetch or an @EntityGraph, instead of making the mapping itself eager everywhere.
05Side by side
| Lazy loading | Eager loading | |
|---|---|---|
| When it loads | On demand — when visible, visited or accessed | Up front — at startup or with the parent query |
| Initial load | Fast and light | Slower and heavier |
| Later interactions | Can show a small delay or spinner | Instant — it's already there |
| Data / memory used | Only what's needed | Everything, used or not |
| Classic pitfall | N+1 queries; layout shift; lazy-loading the hero image | Huge bundles; wasted bandwidth; loading data nobody reads |
| Great for | Long feeds, galleries, rarely used routes, modals, heavy libraries | Above-the-fold content, related data you will render, small critical assets |
There's also a middle ground worth knowing: prefetching. Load lazily, but start fetching during idle time or when the user hovers a link — so by the time they click, it's already there. Next.js does this for links in the viewport, and <link rel="prefetch"> does it in plain HTML.
06Your turn: lazy or eager?
Pick a strategy for each situation.
fetchpriority="high".Order::with('customer') makes it 2.React.lazy or dynamic import(). Everyone else gets a smaller bundle; you can prefetch it when they hover the tab.07Takeaways
- 1Lazy and eager are the same trade-off: pay now or pay later. Choose based on how likely the thing is to be used, and how expensive one fetch is.
- 2On the frontend, lazy-load what's below the fold or behind an interaction, and eager-load what's on the first screen.
- 3In the database, eager-load relationships you're about to render in a loop. Count your queries — N+1 hides until production data arrives.
- 4Use the middle ground: root margins and prefetching make lazy loading feel instant.
- 5Measure, don't guess: the Network tab, Lighthouse, and Laravel Debugbar / Telescope show you exactly what loads and when.