Lazy load images and iframes natively
Defer off-screen images and embeds with loading="lazy", while keeping the main image eager to protect LCP.
- HTML
- GreenSnippets
- MIT
<!-- Above the fold: load immediately and prioritise -->
<img src="/hero.jpg" alt="Product on a desk" width="1200" height="600" fetchpriority="high">
<!-- Below the fold: lazy -->
<img src="/feature.jpg" alt="Dashboard screenshot" width="800" height="450" loading="lazy" decoding="async">
<iframe src="https://www.youtube-nocookie.com/embed/VIDEO_ID" title="Product demo video"
width="560" height="315" loading="lazy" allowfullscreen></iframe>Example / expected output
<!-- Check Network panel: lazy images load only as you scroll. -->How it works
loading="lazy" delays fetching until the element is near the viewport. Always set width and height so the browser can reserve space and avoid layout shift. Do not lazy load the hero image that is visible on first paint; mark it fetchpriority="high" instead.
This snippet has been reviewed but was not executed by an automated test. Test it in your own environment before relying on it.
Related snippets
- Python Tested
Time a block of code with a context manager
Measure elapsed wall-clock time of a with-block using time.perf_counter.
- PHP Tested
Read a large CSV file with a generator
Stream CSV rows as associative arrays using fgetcsv, without loading the whole file into memory.
- JavaScript Tested
Run async tasks with a concurrency limit
Process a large list with at most N promises in flight at once, preserving result order.
- Bash
Run commands in parallel with xargs
Process many files concurrently with xargs -P, safely handling spaces and newlines in names.

