How to make YouTube video lazy load in WordPress without plugins?

How to make YouTube video lazy load in WordPress without plugins?

If you are using YouTube videos on your WordPress site, you can increase your page loading speed by lazy loading the YouTube player.

You can do this by adding one piece of code to your theme`s functions.php. We will use the oembed_dataparse filter for this.

add_filter('oembed_dataparse', function($return, $data, $url) {
    if ($data->provider_name === 'YouTube') {
        return str_replace('src=', 'loading="lazy" src=', $return);
    } else {
        return $return;
    }
}, 20, 3);

In code bellow we add native loading="lazy" attribute to iframe of YouTube player.

Note, lazy loading will be applied to new videos because wordpress caches embed codes. You can clear oEmbed cache for already embeded youtube videos by next sql query:

DELETE FROM `wp_postmeta` WHERE `meta_key` LIKE '_oembed_%' AND `meta_value` LIKE '%youtube%';

Read more