Lazy-loading images is pretty common these days, but did you know you can do the same thing with iframes?
Lazy-loading images and iframes
Baseline 2023 newly available
Supported in Chrome: yes.
Supported in Edge: yes.
Supported in Firefox: yes.
Supported in Safari: yes.
Since December 2023 this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
By deferring offscreen iframes from being loaded until the user scrolls near them, you can significantly improve your site’s performance.
Let’s break down how to implement lazy-loading iframes, why it’s useful, and what browser support looks like.
Before and After: Adding Lazy Loading to Iframes
Here’s an iframe before adding lazy-loading:
Now, let’s add the loading="lazy"
attribute:
That’s it! With just one attribute, the iframe will load only when the user scrolls near it.
Why Lazy-Load Iframes?
Iframes are often used to embed third-party content, like YouTube videos, social media posts, or ads. Most of this content doesn’t appear immediately in the user’s viewport. But when loaded eagerly, users still pay the cost of downloading the iframe’s data and JavaScript, even if they never scroll down to it.
For example, loading a YouTube embed upfront can pull in over 500 KB of resources that users might not even need. By lazy-loading iframes, you defer loading them until users scroll near them. This saves bandwidth and improves page performance, especially for mobile users or those on slower connections.
How Lazy Loading Works
When you add loading="lazy"
to an iframe, the browser delays loading it until it’s close to the user’s viewport. This is particularly useful for content that appears below the fold.
Here’s an example:
Without lazy-loading, this iframe would load as soon as the page starts loading, even if the user never scrolls down to it. But with the loading="lazy
attribute, it only loads when the user approaches it, saving bandwidth and improving your site’s Time to Interactive (TTI).
Browser Support
Lazy-loading for iframes is supported in most modern browsers:
- Chrome: 77+
- Edge: 79+
- Firefox: 121+
- Safari: 16.4+
This wide browser support means you can confidently implement lazy-loading without worrying about breaking your site for most users.