Lazy loading is a loading strategy that makes it possible to load something later. You may know this from Gatsby, React, or for images. Images or iframes below the fold can load later.
In this post, you read about native lazy-loading iframes. I show you how it works and why you should use it.
Third-party embeds vary a lot. You can use an iframe to include video players, social media posts, or ads on your website. Often the iframe is not above the fold in the viewport of the user. Not using lazy-loading iframes would cause the browser to download the third-party resources right away.
Native lazy-loading an iframe is available via the
loading attribute. You can define three values:
lazy- tell the browser you want to lazy-load it
eager- tell the browser to load it right away
auto- the browser can decide to lazy-load it or not
<!-- Lazy-load the iframe --> <iframe src="https://example.com" loading="lazy" width="600" height="400"></iframe> <!-- Eagerly load the iframe --> <iframe src="https://example.com" width="600" height="400"></iframe> <!-- or use loading="eager" to opt out of automatic lazy-loading in Lite Mode --> <iframe src="https://example.com" loading="eager" width="600" height="400"></iframe>
If you don't use the
loading attribute, it will have the same impact as the
loading="eager". Only in Lite Mode Chrome will use the
auto value to decide how it loads the iframe.
var iframe = document.createElement('iframe'); iframe.src = 'https://example.com'; iframe.loading = 'lazy'; document.body.appendChild(iframe);
iframes act a bit differently than images. If an iframe is hidden and meets the following conditions, Chrome won't lazy-load it. Most websites use hidden iframes for analytics or communication purposes.
Hidden iframe conditions:
- The iframe's width and height are 4px or smaller.
- display: none or visibility: hidden is applied.
- The iframe is off-screen using negative X or Y positioning.
The web.dev team collected some case studies with remarkable results.
- Lazy-loading YouTube video embeds (saves ~500KB on initial page load)
<iframe src="https://www.youtube.com/embed/YJGCZCaIZkQ" loading="lazy" width="560" height="315" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
Lazy-loading Instagram embeds (saves >100KB gzipped on initial load)
Lazy-loading Spotify embeds (saves 514KB on initial load)
Native support for lazy-loading iframes makes it easier to improve the performance of websites. The above examples show the impact of media embeds, but you could imagine a massive potential for ads. In this post, you read about native lazy-loading iframes. I showed you how it works and why you should use it.