This is a pretty good resource by tipswithpunch. He runs you through the details of embedding a YouTube video in your HTML in the right way. It’s easy, simple – but mainly; it’s important you do it correctly to make it display in a good way on your site for all your visitors; whether they are using a browser or a mobile phone!
Embedding YouTube the modern way
YouTube’s standard embed code works, but it has two downsides: the full player loads hundreds of kilobytes of scripts on page load – even for visitors who never press play – and it can set cookies before anyone has consented. Three simple improvements fix that.
1. Use the privacy-enhanced domain
Replace www.youtube.com/embed/ with www.youtube-nocookie.com/embed/. YouTube then does not store information about visitors on your page unless they play the video.
2. Make it responsive
<iframe src="https://www.youtube-nocookie.com/embed/VIDEO_ID"
title="Describe the video here"
loading="lazy"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
style="width: 100%; aspect-ratio: 16 / 9; border: 0;"></iframe>The CSS aspect-ratio property keeps the video at 16:9 on every screen width, without the padding hacks of the past. loading="lazy" delays loading until the video is near the viewport, and the title helps screen reader users.
3. Load the player only on click
For the best speed, show a thumbnail with a play button and only insert the iframe when the visitor clicks. That is exactly what we do with the videos on this website. It improves your Core Web Vitals and avoids loading YouTube’s scripts for visitors who are not interested. Read more in how to make your website faster and GDPR and cookie banners.
