Lazy-load offscreen iframes for better Pagespeed

ยท

1 min read

Browser-level lazy-loading for iframes is here. Use loading="lazy" and defers offscreen iframes from being loaded until the user scrolls near them.

<iframe 
    src="https://example.com/"
    loading="lazy"
/>

You can see how lazy loading iframes work with this demo:

Why lazy-load iframes is important?

Based off Chrome's research into automatically lazy-loading offscreen iframes for Data Saver users, lazy-loading iframes could lead to 2-3% median data savings, 1-2% First Contentful Paint reductions at the median, and 2% First Input Delay (FID) improvements at the 95th percentile.

An option for WordPress sites

If you have an iframe inside your posts or pages, you can add the following code to your WordPress theme's functions.php file to automatically insert loading="lazy" to your existing iframes without having to manually update them individually.

function wp_lazy_load_iframes_polyfill( $content ) {
    // If WP core lazy-loads iframes, skip this manual implementation.
    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' );
ย