Lesson 37 of 55 · HTML
Performance – Lazy Loading Images & Iframes
Duration: 9 min
Deferring Resource Loading
Modern browsers support the native loading attribute.
<img src='large.jpg' alt='Large picture' loading='lazy' />
<iframe src='https://example.com' loading='lazy' title='Example site'></iframe>
Elements load only when they approach the viewport, reducing initial page weight and improving Largest Contentful Paint (LCP).
Polyfill for older browsers
if ('loading' in HTMLImageElement.prototype === false) {
const script = document.createElement('script');
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.3.2/lazysizes.min.js';
document.body.appendChild(script);
}
Lazysizes adds the lazyload class to images and iframes that lack native support.
Best practices
- Combine native lazy loading with responsive
srcsetto serve appropriately sized images. - Never lazy‑load above‑the‑fold hero images; they should load immediately.
- Use a blur‑up placeholder or low‑quality image placeholder (LQIP) to avoid layout shift (CLS).
- For iframes, also add
sandboxandallowattributes to improve security.
Quick checklist for lazy loading
loading='lazy'added to off‑screen images/iframes? ✅- Polyfill present for browsers without native support? ✅
- Responsive
srcsetused for images? ✅ - Hero images excluded from lazy loading? ✅
- Placeholder or LQIP used to avoid CLS? ✅
Tip: Test with Chrome DevTools → Network throttling (e.g., Slow 3G) to see the impact on LCP and CLS.