Implementing Smart Lazy Loading
Lazy loading is the practice of delaying the loading of non-critical resources (images, videos, iframes) until the user scrolls down to them. This significantly improves the Initial Load Time and Largest Contentful Paint (LCP).
How It Works
Instead of loading 50 images at once when the page opens, the browser only loads the 3 images visible on the screen. As the user scrolls, the other 47 are fetched one by one.
Step 1: Native Lazy Loading
WordPress 5.5+ includes native lazy loading by default. It adds loading="lazy" to <img> tags.
However, native lazy loading isn't perfect. It relies on the browser's implementation, which can vary.
Step 2: Advanced Lazy Loading (Recommended)
For better control, use a plugin like WP Rocket, Perfmatters, or a dedicated image plugin.
What to Lazy Load:
- Images: Obvious.
- Iframes: YouTube embeds, Google Maps.
- Background Images: Often missed by native lazy loading.
- Comments: Don't load the comments section (and Gravatars) until the user scrolls to the bottom.
Step 3: Lazy Loading YouTube Videos
YouTube embeds are heavy. They load roughly 500KB - 1MB of JS just to show the thumbnail.
Solution: Replace YouTube iframe with preview image.
- In WP Rocket, go to Media.
- Check Enable for iframes and videos.
- Check Replace YouTube iframe with preview image.
Now, the user only downloads the thumbnail (20KB). The heavy YouTube player only loads if they actually click the play button.
Step 4: The "LCP" Pitfall
CRITICAL WARNING: Do NOT lazy load the first image on the page (usually the Featured Image or Hero Background).
If you lazy load the hero image, the browser waits to download it, causing a delay in the Largest Contentful Paint (LCP) metric. This hurts your Google PageSpeed score.
How to Exclude the Hero Image:
- Find the CSS class or filename of your hero image.
- In your lazy load plugin settings, look for Excluded Images.
- Add the filename (e.g.,
hero-banner.jpg) or class.
Conclusion
Lazy loading is essential for media-heavy sites. By implementing smart lazy loading (and excluding the top image), you ensure a lightning-fast initial render.
Next, we will look at DNS Prefetching, a networking trick to speed up external connections.