One of the problems with embedding Youtube videos into your pages is that they load in all sorts of javascript assets along with you page load even if the user doesn’t click to play the video.
One way to get around this is to use an image to represent the video in the page and don’t embed the Youtube video until the user clicks on the image. This can save your page load as much 1mb- 1.5mb per page load.
<img id="thumbnail" src='PATH-TO-IMAGE/placeholder.jpg' alt='IMAGE OR VIDEO TITLE' loading="lazy" style="cursor: pointer;">
<div id="video-container"></div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const thumbnail = document.getElementById('thumbnail');
const videoContainer = document.getElementById('video-container');
// YouTube video ID
const videoId = 'YOUR-YOUTUBE-VIDEO-ID'; // Replace with your video ID
// Embed URL template
const embedURL = `https://www.youtube.com/embed/${videoId}?autoplay=1`;
thumbnail.addEventListener('click', function() {
// Hide Thumbnail
thumbnail.style.display = 'none';
// Insert the YouTube iframe into the video container
videoContainer.innerHTML = `
<iframe width="560" height="315" src="${embedURL}"
title="YouTube video player" frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe>
`;
});
});
</script>
This would get you something like the image/embed content below.
