Iframe lazy loading
The browser Chrome and Chromium-based browsers have a built-in iframe lazy loading support using loading=”lazy” attribute.
<iframe src="https://www.youtube.com/embed/Q4zysy8A_OE" loading="lazy" width="600" height="400"></iframe>
As we know that lazy loading speeds up the page loading, reduces memory usage, and stops unnecessary download of data. The iframe lazy-loading defers offscreen iframes from being loaded until the user scrolls near them. This improves the user experience a lot.
Built-in iframe lazy-loading settings:
The iframe lazy-loading is done using loading
attribute. The loading attribute takes three values:
- lazy: for lazy-loading.
- auto: browser will determine whether or not to do lazy-loading.
- eager: for loading immediately.
Following are some examples of lazy-loading settings:
// loading="lazy" <iframe width="560" height="800" loading="lazy" src="https://www.youtube.com/embed/Q4zysy8A_OE" allow="autoplay;" allowfullscreen></iframe> // loading="eager" <iframe width="560" height="800" loading="eager" src="https://www.youtube.com/embed/Q4zysy8A_OE" allow="autoplay;" allowfullscreen></iframe> // loading="auto" is default so we don't have to mention <iframe width="560" height="800" src="https://www.youtube.com/embed/Q4zysy8A_OE" allow="autoplay;" allowfullscreen></iframe>
Dynamic iframe with lazy-loading support:
We can create a dynamic iframe and set the loading attribute to lazy using JavaScript. Following is the example:
var iframe = document.createElement('iframe'); iframe.src = 'https://www.youtube.com/embed/Q4zysy8A_OE'; iframe.loading = 'lazy'; document.body.appendChild(iframe);