Lazy Loading Images and Code: Best Practices

Native loading="lazy", why never to lazy-load the LCP image, code splitting with prefetch on intent, and reserving space to avoid layout shift.

Lazy loading: common questions

Should I lazy-load every image?

No. Never lazy-load the largest image in the first screen; it delays LCP. Lazy-load images below the fold and give every image width and height.

Related chapters

Keep learning

Overview

Chapter 71 · lazy loading Load it when the reader is about to need it Lazy loading moves bytes out of the first screen. The skill is choosing what moves, and starting early enough that nobody sees the wait.

6. What you decide in production

Native first The viewport, and the distance Chromium starts lazy fetches: about 1250 pixels on fast networks, 2500 on slow. fast net slow net loading="lazy" on <img> and <iframe>. Chromium starts the fetch about 1250px away on fast networks and 2500px on slow ones. No JS, no observer. Never the LCP image A lazy hero starts after layout and finishes late. A high priority hero starts at discovery. LCP sooner Always reserve space Image sizing no size: 0px → 140px, text jumps width + height: box ready at first paint width and height attributes (or aspect-ratio) on every lazy image and every Suspense fallback. A skeleton the same size as the content. Observer for components The sentinel nears the viewport, the widget mounts, then the observer unobserves. nears viewport mount widget Mounting a widget, fetching data, or a custom scroll root: an Intersection Observer with a rootMargin that equals your lead time. Unobserve after the first hit. Prefetch on intent The download starts on hover, so most of it is done before the click. on click on hover Hover, focus, or a link entering the viewport starts import(). Idle-time prefetch for likely next routes. Skip it when navigator.connection.saveData is on. Chunks vanish on deploy An old tab asks for a deleted chunk, gets a 404, and reloads once. old tab reload once An open tab asks for Editor.81ab.js after you deleted it. Keep old chunks for a few days, and catch a failed import() with one reload. Not too small An 8 KB chunk is almost all round trip. A 200 KB chunk is mostly bytes worth deferring. round trip bytes saved Each split costs a request and a render pass. Below ~20 KB, a round trip costs more than the bytes you saved. Split routes and heavy widgets, not buttons. Invisible to some readers Who sees scroll-loaded content find-in-page, print, non-scrolling crawlers server-rendered text, lazy media

1. Twenty-four photos, one screen

Each photo is 120 KB and takes 450ms to arrive. Scroll, then fling. <img loading> Reload page Eager: every photo competes with the first screen for bandwidth, including the ones nobody scrolls to. A short distance saves bytes, but a fling outruns it and the reader sees blanks. A long distance starts each photo well before it arrives. Fewer blanks, a few more bytes. Photo feed not requested Fling down fetched ahead of the reader blank on screen waits for layout low priority high priority Main thread A lazy image cannot start until layout proves it is near the viewport. Layout waits for CSS. The hero joined the queue one round trip late. Requested at discovery, but images start at low priority. It shared the pipe with CSS until layout boosted it. Requested at discovery at high priority. The download overlaps the CSS. This is the shortest LCP.

2. Never lazy-load the image the reader sees first

Hero <img> default (eager) First paint In main bundle On click On hover / focus On idle

3. Lazy code: choose when you pay

Load the editor Reader clicks at Strategies compared Strategy Page interactive Wait after click Instant editor, but every visitor downloads and parses 180 KB before the page responds. Fastest page. The reader who clicks stares at a skeleton for a full download. The pointer reaches the button ~300ms before the click. That head start comes off the wait for free. The page stayed fast, but 180 KB was spent on a feature nobody opened. The page was fast and the editor was already there when the click came. Over half a second: show a skeleton the size of the editor.

4. A late image must not move the page

The <img> has no size width + height Image arrives The image appeared and pushed the text and button down. The text and button stay in place. Weekend in Lisbon Three days, one tram line, too many pastries. Book this trip Zero-height box became 140px. The text and the button moved under the reader’s thumb. That is CLS. The box has no height yet. Load the image. route chunk started by the router chart chunk useEffect fetch lazy inside

5. Lazy boundaries hide waterfalls

Each lazy piece is discovered only after the piece before it renders. Requests start When each parent renders Together, from the route The router knows the route needs data and the chart. It starts all three at once: one round trip. Chunk, then render, then fetch, then render, then another chunk. Three round trips in a row.

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
  • Databases in depth — How a query becomes work. Indexes, isolation, locks, and the plans that explain why a page is slow — not an ORM tour.
  • System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.