HomeMethod

Knowledge

Web VitalsTechniquesSnippetsAnswersImpactsBottlenecks

Native lazy loading for iframes

  • Performance

Every iframe on your page loads an entire document — its own HTML, CSS, JavaScript, images, and fonts. A single YouTube embed can add 500+ KB to your page weight. If the iframe isn’t visible on first load, that’s bandwidth and CPU wasted on something the user hasn’t seen yet.

lazy-load-iframes.php
<?php
/**
 * Add Native Lazy Loading to Iframes
 *
 * Iframes (YouTube embeds, Google Maps, etc.) are expensive — each one loads
 * an entire document with its own CSS, JS, and images. Native lazy loading
 * defers this until the iframe scrolls near the viewport, saving significant
 * bandwidth and improving initial page load. WordPress adds loading="lazy"
 * to images automatically since 5.5, but does not do the same for iframes.
 *
 * Usage: Add to functions.php.
 *
 * @category performance
 * @language php

 *
 * @author Adame Dahmani https://adame.io
 * @support Support my family project: https://adame.io/fundraiser
 */
add_filter( 'the_content', function ( $content ) {
    if ( is_admin() || is_feed() ) {
        return $content;
    }

    return preg_replace(
        '/<iframe((?!.*loading=)[^>]*)>/i',
        '<iframe$1 loading="lazy">',
        $content
    );
} );

Native lazy loading (loading="lazy") defers the iframe until it approaches the viewport. WordPress has done this for images since 5.5, but iframes are still left out. This filter adds it automatically to all iframes in post content.

Support our family now