Performance · Web & Backend

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.

Kavindu Praneeth·Oct 22, 2026·9 min read
Eager downloads all 8 images at page load0 KB
Lazy downloads only what's near the viewport0 KB
Viewport
Not requestedDownloadingLoaded

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.

Scroll me ↓
Requests
0
Downloaded
0 KB
First screen
—
Never seen
0 KB
Network waterfall0.0 s
Waiting / queuedDownloadingBold name = user actually saw it

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.

🧩AppLaravel
query →← rows
🛢️DBMySQL


    
Queries executed
0
For 8 authors, at ~20 ms per round-trip:
Lazy · N+1
180 ms
Eager · 2
40 ms
    -- 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 loadingEager loading
When it loadsOn demand — when visible, visited or accessedUp front — at startup or with the parent query
Initial loadFast and lightSlower and heavier
Later interactionsCan show a small delay or spinnerInstant — it's already there
Data / memory usedOnly what's neededEverything, used or not
Classic pitfallN+1 queries; layout shift; lazy-loading the hero imageHuge bundles; wasted bandwidth; loading data nobody reads
Great forLong feeds, galleries, rarely used routes, modals, heavy librariesAbove-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.

🖼️ The big hero banner at the very top of your landing page.
It's visible immediately and is usually the Largest Contentful Paint. Lazy-loading it makes the browser wait for layout before even starting — load it eagerly with fetchpriority="high".
📸 An event gallery with 200 photos on one page.
Most visitors see the first dozen. Lazy-loading saves them megabytes and keeps the first screen fast.
🧾 An admin table of 50 orders, each row showing the customer's name.
You will render the customer for every row, so lazy access would fire 51 queries. Order::with('customer') makes it 2.
📊 A 300 KB charting library used only on the "Reports" tab.
Code-split it with React.lazy or dynamic import(). Everyone else gets a smaller bundle; you can prefetch it when they hover the tab.
Score: 0 / 4

07Takeaways

Read next
🚨 Security · Oct 23, 2026October 2026 Security RoundupNine advisories explained, with fixed versions and a patch checklist.