Lazy Load YouTube Embeds in WordPress to Improve Page Speed (Without a Plugin)
Embedding YouTube videos in your WordPress posts is easy — but it can significantly slow down your website. Each YouTube <iframe>
loads several external scripts, even before the user presses play. This impacts your page's Time to Interactive (TTI) and Core Web Vitals scores.
In this tutorial, you'll learn how to replace default YouTube embeds with lightweight preview thumbnails that only load the actual video player on demand — improving page speed and user experience without using a plugin.
🎯 What We’ll Do
-
Replace standard
<iframe>
YouTube embeds with a thumbnail + play button -
Load the actual YouTube player only after the user clicks
-
Use
the_content
filter to process video links dynamically
✅ Step 1: Convert YouTube Links into Custom HTML
In your theme’s functions.php
or custom plugin, hook into the_content
and detect YouTube URLs.
function lazyload_youtube_embeds($content) {
return preg_replace_callback(
'#https?://(?:www\.)?youtube\.com/watch\?v=([^\s&]+)#',
function ($matches) {
$video_id = esc_attr($matches[1]);
$thumbnail = "https://img.youtube.com/vi/{$video_id}/hqdefault.jpg";
ob_start(); ?>
<div class="lazy-youtube" data-id="<?php echo $video_id; ?>">
<img src="<?php echo $thumbnail; ?>" alt="YouTube Thumbnail" />
<button class="play-button" aria-label="Play video"></button>
</div>
<?php
return ob_get_clean();
},
$content
);
}
add_filter('the_content', 'lazyload_youtube_embeds');
✅ Step 2: Add JavaScript to Load the <iframe>
on Click
Now enqueue a small JavaScript snippet that replaces the thumbnail with the actual embedded player.
function enqueue_lazy_youtube_script() {
?>
<script>
document.addEventListener("DOMContentLoaded", function () {
document.querySelectorAll(".lazy-youtube").forEach(function (container) {
container.addEventListener("click", function () {
const videoId = container.dataset.id;
const iframe = document.createElement("iframe");
iframe.setAttribute("src", "https://www.youtube.com/embed/" + videoId + "?autoplay=1");
iframe.setAttribute("frameborder", "0");
iframe.setAttribute("allowfullscreen", "");
iframe.setAttribute("allow", "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture");
container.innerHTML = "";
container.appendChild(iframe);
});
});
});
</script>
<style>
.lazy-youtube {
position: relative;
width: 100%;
max-width: 720px;
aspect-ratio: 16/9;
cursor: pointer;
background: #000;
overflow: hidden;
}
.lazy-youtube img {
width: 100%;
display: block;
}
.lazy-youtube .play-button {
position: absolute;
top: 50%;
left: 50%;
width: 64px;
height: 64px;
background: url('https://img.icons8.com/ios-filled/50/ffffff/play-button-circled.png') no-repeat center center;
background-size: contain;
border: none;
transform: translate(-50%, -50%);
opacity: 0.8;
}
</style>
<?php
}
add_action('wp_footer', 'enqueue_lazy_youtube_script');
💡 You can host the play icon locally or use any SVG you prefer.
✅ Step 3: Use YouTube Links in Your Content
Now, just paste raw YouTube links like this inside any post:
https://www.youtube.com/watch?v=ScMzIvxBSi4
And WordPress will automatically convert them into a lazy-loaded preview that looks like a video but doesn’t load the actual player until clicked.
🔍 Performance Comparison
Before | After Lazy Loading |
---|---|
DOM Size: Large | DOM Size: Minimal |
Scripts loaded immediately | Scripts loaded on click |
Slower mobile score | Faster mobile performance |
You can test improvements using PageSpeed Insights.
🧠 Summary
Lazy loading YouTube videos is a high-impact performance optimization, especially for content-heavy or mobile-first sites. This approach:
-
Reduces initial page load time
-
Improves Core Web Vitals
-
Keeps your HTML clean and accessible
-
Requires no external plugins
Want to extend this to support short YouTube links or playlists? Let me know — I can help you expand the code!
Convenient hosting for your WordPress sites
Looking for good hosting for your WordPress sites? Pay attention to Host4Biz. It is a reliable hosting with modern servers in Europe and a Ukrainian team.
And with the promo code MYHOST10 you will get a 10% discount on your first payment. To do this, register here and enter the code before paying.
Note: There are affiliate links in the link given above and if you buy something, I’ll get a commission at no extra cost to you.
Read also: Best Digital Agency WordPress Themes (Mostly Free) https://medium.com/@wwwebadvisor/best-digital-agency-wordpress-themes-mostly-free-a4f64e0bd03f
Comments
Post a Comment