Skip to main content




La carga diferida nativa a nivel del browser para iframes está aquí

The native lazy loading for landed images in Chrome 76 via loading attribute y luego llegó a Firefox. Estamos felices de compartir eso
native lazy loading for iframes is now
standardized y también es compatible con los browsers Chrome y Chromium.

<iframe src="https://example.com"
loading="lazy"
width="600"
height="400">
</iframe>

La carga diferida nativa de iframes difiere la carga de iframes fuera de la pantalla hasta que el Username se desplaza cerca de ellos. Esto ahorra datos, acelera la carga de otras partes de la página y reduce el uso de memoria.

Is manifestation from <iframe loading=lazy>
shows lazy loading video embeds:


Why should we lazily load iframes?

Las incrustaciones de terceros cubren una amplia gama de casos de uso, desde reproductores de video hasta publicaciones en redes sociales y anuncios. A menudo, este contents no es inmediatamente visible en la ventana gráfica del usuario. Más bien, solo se ve una vez que se desplazan hacia abajo en la página. A pesar de esto, los usuarios pagan el costo de descargar datos y JavaScript costoso por cada marco, incluso si no se desplazan hasta él.

iframe-lazyloading-6365905

Based on Chrome's research on iframes off screen lazy loading automatically for Data Saver users, lazy loading iframes could result in average data savings of 2-3%, first paint reductions with 1-2% content in the median, and 2% improvements in first entry delay (FID) at the 95th percentile .

How does native lazy loading work for iframes?

the loading The attribute allows a browser to defer the loading of iframes and images off the screen until users scroll close to them. loading supports three values:

  • lazy: is a good candidate for lazy loading.
  • eager: not a good candidate for lazy loading. Charge immediately.
  • car: the browser will determine if it loads lazy.

car It is currently a non-standard value, but it is the default in Chrome today. Chrome intends to bring a proposition of this value to the standards table.

Using the loading attribute in iframes works as follows:


<iframe src="https://example.com"
loading="lazy"
width="600"
height="400">
</iframe>


<iframe src="https://example.com"
width="600"
height="400">
</iframe>


<iframe src="https://example.com"
loading="eager"
width="600"
height="400">
</iframe>

Not specifying the attribute at all will have the same impact as explicitly loading the resource with enthusiasm, except for The light mode
users, where Chrome will use the car value to decide if it should be lazy loaded.

If you need it dynamically create iframes via JavaScript, setting
iframe.loading = 'lazy' in the element is also
supported:

var iframe = document.createElement('iframe');
iframe.src = 'https://example.com';
iframe.loading = 'lazy';
document.body.appendChild(iframe);

Iframe specific lazy loading behavior

The load attribute affects iframes differently than images, depending on whether the iframe is hidden. (Hidden iframes are often used for analytical or communication purposes.) Chrome uses the following criteria to determine if an iframe is hidden:

  • The width and height of the iframe are 4px or less.
  • display: none or visibility: hidden It is applied.
  • El iframe se coloca fuera de la pantalla mediante un positioning X o Y negativo.
  • This criterion applies to both loading = lazy and loading = auto.

If an iframe meets any of these conditions, Chrome considers it hidden and will not lazy load it in most cases. Iframes that are not hidden will only load when they are within the loading distance threshold. Chrome shows a placeholder for lazy-loaded iframes that are still retrieving.

¿Qué pasaría si pudiéramos cambiar la Web en general para que los iframes fuera de pantalla de carga diferida fueran los predeterminados? Se vería un poco así:

Incrustaciones de videos de Youtube de carga diferida (ahorra ~ 500 KB en la carga de la página inicial):

<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>

Anecdote: When we switched to lazy loading YouTube embeds for Chrome.com, we saved 10 seconds from how quickly our pages could be interactive on mobile devices. I opened an internal error with YouTube to discuss how to add
loading = lazy to your embed code.

iframe-chromecom-3805627

If you are looking for more efficient ways to upload YouTube embeds, you may be interested in the YouTube lite component.

Inserciones de Instagram de carga diferida (ahorra> 100 KB en gzip en la carga inicial):

Instagram embeds provide a markup block and script, which injects an iframe into your page. Lazy loading this iframe avoids having to load all the script required for the insert. Since such embeds are often shown below the viewport in most articles, this seems like a reasonable candidate for native lazy loading of your iframe.

Incrustaciones de Spotify de carga diferida (ahorra 514 KB en la carga inicial):

<iframe src="https://open.spotify.com/embed/album/1DFixLWuPkv3KT3TnV35m3" 
loading="lazy"
width="300"
height="380"
frameborder="0"
allowtransparency="true"
allow="encrypted-media">
</iframe>

Although the embeds above illustrate the potential benefits of lazy-loading iframes for media content, there is a chance to see these benefits in ads as well.

Estudio de caso: carga diferida nativa de los complementos sociales de Facebook

From Facebook social plugins Allow developers to embed Facebook content on their web pages. Several of these plugins are offered, such as embedded posts, photos, videos, comments ... The most popular is the As a complement - a button that shows a count of who has 'liked' the page. By default, embedding the Like plugin on a web page (using the FB JSSDK) pulls ~ 215KB of resources, 197KB of which is JavaScript. In many cases, the plugin may appear at the end of an article or near the bottom of a page, so enthusiastically loading it when off-screen may not be optimal.

fblike-3107047

Thanks to engineer Stoyan Stefanov, all facebook social plugins now support native iframe lazy loading. Developers opting for lazy loading via plugins data-lazy
La configuración ahora podrá evitar que se cargue hasta que el usuario se desplace cerca. Esto permite que la inserción siga funcionando completamente para los usuarios que la necesitan, al tiempo que ofrece ahorros de datos para aquellos que no se desplazan hacia abajo en una página. Tenemos la esperanza de que esta be la primera de muchas incorporaciones para explorar la carga diferida de iframe nativa en producción.

Wait, can't browsers just auto load off-screen iframes lazily?

They certainly can. In Chrome 77, Chrome added support for off-screen images and lazy loading iframes natively when a user has opted for
The light mode
(Data Saving Mode) in Chrome for Android.

Basic mode is commonly used in regions of the world where the quality of the network connection and data plans are not the best. Every byte is important, and therefore lazy-loading iframes have the potential to make a significant difference for these users.

Origins puede detectar qué porcentaje de su traffic proviene de los usuarios del modo básico marcando el navigator.connection.saveData property, which is part of the NetworkInformation API.

Can I lazy load iframes across multiple browsers? Yes

La carga diferida de iframe nativa se puede aplicar como una progressive improvement. Navegadores que admiten loading = lazy in iframes it will lazy load the iframe, while the loading The attribute will be safely ignored in browsers that don't support it yet.

It is also possible to lazy load off-screen iframes using the JavaScript library lazysizes. This may be desirable if:

  • require more custom lazy loading thresholds than native lazy loading currently offers
  • We want to provide users with a consistent iframe lazy loading experience across browsers.

<script src="lazysizes.min.js" async></script>

<iframe frameborder="0"
class="lazyload"
allowfullscreen=""
width="600"
height="400"
data-src="//www.youtube.com/embed/ZfV-aYdU4uE">

</iframe>

Use the following pattern to detect lazy loading function and get lazy sizes when it is not available:

<iframe frameborder="0"
class="lazyload"
loading="lazy"
allowfullscreen=""
width="600"
height="400"
data-src="//www.youtube.com/embed/ZfV-aYdU4uE">

</iframe>

<script>
if ('loading' in HTMLIFrameElement.prototype) {
const iframes = document.querySelectorAll('iframe[loading="lazy"]');

iframes.forEach(iframe => {
iframe.src = iframe.dataset.src;
});

} else {

const script = document.createElement('script');
script.src =
'https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.2.2/lazysizes.min.js';
document.body.appendChild(script);
}

</script>

Una opción para los usuarios de WordPress

You might have a lot of iframes scattered over years of posting content on a WordPress site. Optionally, you can add the following code to your WordPress theme functions.php file to auto insert loading = "lazy" to your existing iframes without having to manually update them individually.

Note that Work is also underway on native support for lazy loading iframes in the WordPress core. The following snippet will search for the relevant flags so that once WordPress has the functionality built in, it will no longer manually add the loading = "lazy" attribute, making sure it is interoperable with those changes and will not result in a duplicate attribute.


function wp_lazy_load_iframes_polyfill( $content ) {
if ( function_exists( 'wp_lazy_loading_enabled' ) && wp_lazy_loading_enabled( 'iframe', 'the_content' ) ) {
return $content;
}

return str_replace( '<iframe ', '<iframe loading="lazy" ', $content );
}
add_filter( 'the_content', 'wp_lazy_load_iframes_polyfill' );

Si su sitio de WordPress utiliza almacenamiento en cache (pista: debería), no olvide reconstruir el caché de su sitio después.

conclusion

Baking in native support for lazy loading iframes makes it much easier for you to improve the performance of your web pages. If you have any comments on native iframe lazy loading feel free to submit a problem to Chrome Bug Tracker.

And in case you missed it, check out web.dev's collection of lazy loading images and videos for more lazy loading ideas.

Our thanks to Dom Farolino, Scott Little, Houssein Djirdeh, Simon Pieters, Kayce Basques, Joe Medley, and Stoyan Stefanov for their reviews.