{"canonical_url":"https://engineer.company/glossary/lazy-loading/","content_markdown":"# Lazy loading\n\n## What it is\n\nLazy loading means putting off the fetching of something until the moment it is\nneeded, instead of loading everything up front. On a web page it usually means\nimages and embedded frames further down, which are fetched only as the reader\nscrolls towards them. The same idea applies to code that runs only after a\nclick, and to the related records an application reads from a database.\n\nThe HTML Standard builds it into the markup. Images and iframes take a `loading`\nattribute with two values. `eager`, the default, fetches the resource straight\naway. `lazy` is, in the standard's words, “used to defer fetching a resource\nuntil some conditions are met.” The standard defines the same attribute on\n`audio` and `video` as well. A missing or misspelled value counts as `eager`, so\na typo leaves the page loading the way it always did.\n\nThe condition is that the element comes close to the viewport. Each document has\nan intersection observer of its own for this job, and when it reports a lazy\nelement about to come into view, the browser resumes loading it. That observer\nlooks a little beyond the visible area, so that an image can arrive while the\nreader is still scrolling towards it, and the standard leaves the size of that\nmargin to the browser.\n\nPages can use the same mechanism directly. The W3C's Intersection Observer\nspecification lets a script ask to be told, asynchronously, when an element\nstarts or stops intersecting the viewport or another element, and it names\ncustom deferred loading of content and data among the practices it was written\nto support. It covers what the attribute does not: a background image set in\nCSS, a map that needs its own script, a list that fetches its next page when the\nreader reaches the end.\n\nFor code, the unit is a module. The Next.js documentation presents lazy loading\nas a way to cut the JavaScript needed to render a route: client components and\nlibraries are left out of the first bundle and fetched when they are needed, its\nexample being a dialog that loads only once someone clicks to open it. Its\n`next/dynamic` combines React's `lazy()` and `Suspense`, and a plain `import()`\ncall does the same for a library.\n\nThe term is older than any of this. In Martin Fowler's catalogue of enterprise\napplication patterns, Lazy Load leaves a marker where related data would go and\nfetches that data only if something uses it, so that reading one object from a\ndatabase does not pull in a large web of other objects nobody looks at. An ORM\nworks this way when it fetches a related record the first time code touches it.\nDjango does so by default: a field that was not part of the original query is\nread from the database when it is first accessed, which its documentation\ndescribes without using the name.\n\nLazy loading is not caching, which keeps a copy of something already fetched so\nit can be used again. It is the opposite of preloading: a `\u003clink rel=\"preload\"\u003e`\ntells the browser to fetch a resource ahead of time, because the page is very\nlikely to need it.\n\n## Why it matters\n\nA page pays for every byte it asks for, whether or not anyone sees it. A long\narticle with forty photographs, a footer with an embedded map and a product page\nwith a video near the bottom all spend bandwidth, battery and connection time on\ncontent that some readers never scroll to. With lazy loading, those requests are\nmade only for the readers who get that far, and what the first screen needs does\nnot have to share the connection with them.\n\nHow early is early enough is left to the browser. The standard suggests that the\nmargin take account of how fast the reader is scrolling and how good the network\nis, with a wider margin on slow or high-latency connections, so that images are\nin place by the time they scroll into view. It also requires that the margin not\nleak information that could be used to fingerprint the reader.\n\nThere is a privacy rule built in as well. Browsers lazy-load only when scripting\nis enabled. Otherwise, the standard explains, a site could scatter images\nthrough its markup and work out roughly how far each reader scrolled from which\nimages the server is asked for, and when. With scripting off, `loading=\"lazy\"`\nquietly becomes an ordinary load.\n\nFor code, Next.js puts the gain in terms of the first load: less JavaScript\nneeded before a route can render. A charting library used on one tab, or a rich\ntext editor behind an Edit button, need not slow down every other page.\n\nIn an ORM the gain is in what is never read. Fowler's point is that loading an\nobject together with everything related to it is convenient until it means\nloading a huge number of objects when only a few are wanted, and Lazy Load\nbreaks that chain.\n\n## What it looks like in practice\n\nFor images and frames, the attribute does the work. The image and the map below\nsit far down a page, so both can wait:\n\n```html\n\u003cimg\n  src=\"/photos/harbour-800.jpg\"\n  srcset=\"/photos/harbour-800.jpg 800w, /photos/harbour-1600.jpg 1600w\"\n  sizes=\"auto, 100vw\"\n  width=\"1600\"\n  height=\"900\"\n  alt=\"Fishing boats in the harbour at dawn\"\n  loading=\"lazy\"\n/\u003e\n\n\u003ciframe\n  src=\"/embeds/route-map.html\"\n  title=\"Map of the walking route\"\n  width=\"640\"\n  height=\"360\"\n  loading=\"lazy\"\n\u003e\u003c/iframe\u003e\n```\n\n`width` and `height` give the image its proportions before any of it has\narrived: the HTML rendering rules map the two numbers to an aspect ratio, so the\nbrowser can hold a box of the right shape. `sizes=\"auto\"` is allowed only on a\nlazy image. It tells the browser to choose from `srcset` by the width the image\nis actually laid out at, which a lazy image has by the time it is fetched, and\nthe `100vw` after it is the fallback when that width cannot be worked out.\n\nSome lazy loading needs a script. Here a map library is fetched only when its\ncontainer is about to scroll into view:\n\n```js\nconst box = document.querySelector(\"#route-map\");\n\nconst observer = new IntersectionObserver(\n  async (entries) =\u003e {\n    if (!entries.some((entry) =\u003e entry.isIntersecting)) return;\n    observer.disconnect();\n    const { drawMap } = await import(\"./route-map.js\");\n    drawMap(box);\n  },\n  { rootMargin: \"200px 0px\" },\n);\n\nobserver.observe(box);\n```\n\nThe `rootMargin` grows the viewport by 200 pixels at the top and bottom for this\ncheck, so the module starts loading shortly before the box is visible. The\ncallback runs asynchronously and can report several entries at once, and it\nchecks `isIntersecting` because the observer also reports elements that are\noutside the area. Disconnecting first means the callback does its work once,\nhowever often the reader scrolls past. Until then, `route-map.js` is not part of\nthe page at all.\n\nFonts can be split so that a browser fetches only the parts a page uses, with no\nscript involved.\n[A note on this site about a Safari underline bug](/notes/safari-underline-font-subset/)\nrecords how the site's Ubuntu typeface was then served as six files, three weights\nfor Latin text and three for Cyrillic, each of them stating the range of\ncharacters it covers. The browser routes Latin prose to the Latin cuts and\nCyrillic prose to the Cyrillic ones. A Cyrillic language label can\ntherefore need a Cyrillic cut on an otherwise English or Danish page. The note\ndoes not call this lazy loading, but the same need-driven choice keeps an unused\ncut out of the page's font requests unless it is explicitly preloaded.\n\nThe files every page needs at once call for the opposite decision.\n[A portfolio entry on cutting the stylesheet bundle](/portfolio/cut-the-stylesheet-bundle-from-87-kb-to-31-kb/)\nexplains why a font embedded in the stylesheet as base64 was taken out. It had\nbeen put there to speed up the first paint, but a separate file that is\npreloaded gives the same benefit, while the embedded copy added its weight to\nevery page, needed there or not. At that stage, three weights of the font were preloaded\ninstead, and the entry notes that field data, not a sense of completeness, put\nthe third one on that list. Lazy loading and preloading are two sides of one\njudgement: what the first screen needs comes early, and the rest waits its turn.\n\n## Where it goes wrong\n\n**The first image arrives last.** A lazy image waits for more than the network.\nIts fetch resumes only when the browser's observer reports it near the viewport,\nand observers are updated as part of rendering a frame, after style and layout.\nFor a photograph far down the page that wait costs nothing. For the large image\nat the top, it delays the one picture every visitor sees. Leave `loading` off,\nor set it to `eager`, for anything that can appear in the first screen on a\nphone or a desktop, and keep `lazy` for what comes below.\n\n**The page jumps as images land.** An image without `width` and `height` has no\nknown shape until its file arrives, and then pushes everything below it down.\nWith lazy loading that happens while the reader is scrolling, often in the\nmiddle of a sentence. Give every image its dimensions in the markup or in CSS.\nFor `sizes=\"auto\"` the HTML Standard is explicit: without stated dimensions such\nan image will likely be drawn at 300 by 150 pixels, so it strongly encourages\ngiving them.\n\n**Images that need a script to exist.** A hand-made version puts the real\naddress in a `data-src` attribute and lets a script copy it into `src` when the\nimage comes near. If that script does not load, throws an error or is blocked,\nthe image never appears, and anything that reads the markup without running\nscripts sees an image with no source. The built-in attribute fails the other\nway: with scripting disabled, the standard has the browser load the image\nstraight away. Use `loading=\"lazy\"` for images and frames, and keep scripts for\nwhat the attribute does not cover.\n\n**Deferring what every visit needs.** Lazy loading pays off when much of what is\ndeferred is never used. When everything will be used, it only splits one fetch\ninto many. A loop that reads a related record for each item in a list sends a\nseparate query for each: Django's documentation counts one query for the list\nplus one per item in its default mode, and calls the result the N+1 queries\nproblem. A page whose components each request their own data as they appear does\nthe same over the network. Load what is certain to be needed together with the\nlist, in one query or one request, and save lazy loading for what is likely to\nbe skipped.\n\n## Further reading\n\n- [HTML Standard: Lazy loading attributes](https://html.spec.whatwg.org/multipage/urls-and-fetching.html#lazy-loading-attributes)\n  — the `lazy` and `eager` keywords, the browser's own intersection observer\n  and the rule that switches lazy loading off without scripting.\n- [Intersection Observer](https://www.w3.org/TR/intersection-observer/)\n  — the W3C working draft behind the observer: roots, margins, thresholds and\n  how callbacks are queued.\n- [How to lazy load Client Components and libraries](https://nextjs.org/docs/app/guides/lazy-loading)\n  — `next/dynamic`, `React.lazy()` with `Suspense`, skipping server rendering\n  and loading a library with `import()`.\n- [Lazy Load](https://martinfowler.com/eaaCatalog/lazyLoad.html)\n  — Martin Fowler's pattern from Patterns of Enterprise Application\n  Architecture, with its four varieties.\n- [Fetch modes](https://docs.djangoproject.com/en/stable/topics/db/fetch-modes/)\n  — how Django fetches fields that were not loaded with the original query,\n  and the modes that batch or block those fetches.\n\n\u003chttps://engineer.company/glossary/lazy-loading/\u003e\n","date_modified":"2026-11-12T05:34:23Z","description":"Fetching images, frames, code or related records only when they are needed: the HTML attribute, observers, dynamic imports and four ways it goes wrong.","formats":{"gemtext":"https://engineer.company/glossary/lazy-loading/index.gmi","gopher":"https://engineer.company/glossary/lazy-loading/gophermap","html":"https://engineer.company/glossary/lazy-loading/","json":"https://engineer.company/glossary/lazy-loading/index.json","markdown":"https://engineer.company/glossary/lazy-loading/index.md","pdf":"https://engineer.company/glossary/lazy-loading/index.pdf"},"kind":"page","language":"en","title":"What is lazy loading?","url":"https://engineer.company/glossary/lazy-loading/","version":1}