Have you ever noticed how long it takes for your web page to load when you have embedded YouTube videos?
Or any heavy JavaScript payload?
The impact of these videos on your page's performance can be significant, especially when you have multiple videos on a single page. This can cause frustration for your visitors who want to access your content quickly. Fortunately, there is a solution to this problem: lazy loading. By implementing this technique, you can reduce the load time of your page and improve the overall user experience.
In this article, we'll explore the concept of lazy loading and how it can help you to speed up your page with embedded YouTube videos. You will see how YouTube loading can be mitigated by delaying its heavy scripts till the user wants to watch the video. This way you can delay loading the video until it is required.
At the moment I am working with the team to create the next version of C# Corner. Part of that update is to make the video more prominent. We also want to improve page speed. This means the site must have a way to lazy load YouTube video scripts. That is what I am going to share with you today.

What is Lazy Loading?
Lazy loading is a technique that allows web developers to defer the loading of certain resources until they are actually needed. In the context of YouTube embeds, lazy loading allows you to delay the loading of the heavy YouTube player script until the user interacts with the video. This can significantly improve page performance, especially on pages with multiple videos.
The way it works is simple: instead of loading the entire YouTube player script when the page loads, you load a small placeholder image or a thumbnail of the video. Then, when the user clicks on the thumbnail, the YouTube player script is loaded, and the video starts playing.
The benefits of lazy loading are numerous. First, it reduces the page loading time, which can help improve the user experience and keep visitors engaged. Second, it reduces the amount of data transferred, which can help reduce bandwidth costs. Finally, it can help improve the search engine rankings of your pages by improving the page speed scores.
Here's an example of the simple lazy loading module, the new site will use. You are welcome to use the module to implement lazy loading on your pages too:
(function (window, undefined) {
function initialize() {
let n,
v = document.querySelectorAll(".youtube-player, .video-hero-container");
for (n = 0; n < v.length; n++) {
if (!v[n].dataset.clickHandler || v[n].dataset.clickHandler !== "true") {
v[n].dataset.clickHandler = "true";
v[n].addEventListener("click", triggerVideoPlayer);
}
}
}
function triggerVideoPlayer(e) {
e.preventDefault();
let videoId = e.currentTarget.dataset.id;
// load YouTube API script
let tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
let firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// create container element for player
let playerContainer = document.createElement('div');
playerContainer.className = 'player-container';
e.currentTarget.parentNode.replaceChild(playerContainer, e.currentTarget);
// get dimensions of the container
let containerWidth = playerContainer.offsetWidth;
let containerHeight = containerWidth * 0.5625; // 9/16
// initialize player
let player;
window.onYouTubeIframeAPIReady = function () {
player = new YT.Player(playerContainer, {
height: containerHeight,
width: containerWidth,
videoId: videoId,
events: {
'onReady': onPlayerReady
}
});
}
// start playing when player is ready
function onPlayerReady(event) {
event.target.playVideo();
}
return false;
}
initialize();
window.lazyYT = {
initialize: initialize
};
})(window);
This module will automatically detect all the YouTube embeds on your page and replace them with a lightweight placeholder. When the user clicks on the placeholder, the script will load the YouTube player script and start playing the video.
It also exposes the initialize method so you can set up lazy loading on any new HTML you might add to the page after it loads. Just call lazyYT.initialize(); to bind the process to any new video placeholders.
Here is an example of what a video looks like in HTML:
<div class="video-card">
<div class="video-list-item youtube-player" data-id="lChoEaj3RnI">
<img src="https://img.youtube.com/vi/lChoEaj3RnI/sddefault.jpg"
srcset="https://img.youtube.com/vi/lChoEaj3RnI/maxresdefault.jpg 1280w,
https://img.youtube.com/vi/lChoEaj3RnI/sddefault.jpg 640w,
https://img.youtube.com/vi/lChoEaj3RnI/mqdefault.jpg 480w,
https://img.youtube.com/vi/lChoEaj3RnI/hqdefault.jpg 320w,
https://img.youtube.com/vi/lChoEaj3RnI/default.jpg 120w"
sizes="(min-width: 1280px) 1280px, (min-width: 640px) 640px, (min-width: 480px) 480px, (min-width: 320px) 320px, 120px"
alt="GitHub Actions vs Azure DevOps pipelines: Explore The Best Option For Your Deployment"
loading="lazy" class="video-list-img" />
</div>
<div class="video-list-item-body">
<p class="recent-post-description">Tempore dignissimos ad debitis sit. Adipisci
molestiae totam quibusdam tenetur ullam neque. In dignissimos soluta
repellendus occaecati fuga illum. Maiores quia consequatur accusantium
fugit.</p>
<h5>GitHub Actions vs Azure DevOps pipelines: Explore The Best Option For Your
Deployment</h5>
<div class="video-list-item-detail-row"> <span class="author-row-item"><i
class="fa-regular fa-clock"></i>2022-09-02 15:58:40.920 </span>
</div>
</div>
</div>


Join the conversation! Your thoughts help the community grow.