Optimizing YouTube embeds

Optimizing YouTube embeds

I was working on this project where speed metrics are very important. On one of the pages, a couple of YouTube videos were added, but these really killed the PageSpeed score. We had to do something about it, and this is what I will explain in this article.

Lazy loading the iframe

loading="lazy" is slowly becoming a possible solution to avoid loading the iframe if it's not displayed. I'm not sure why it's not added by default in the embed markup, but I see no reason not to do it.

<iframe 
width="560" height="315" loading="lazy" 
src="https://www.youtube.com/embed/ogfYd705cRs" 
title="YouTube video player" frameborder="0" 
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen>
</iframe>

Loading less scripts

Digging deeper, I found this article about lazy load embedded YouTube videos. It shows a really neat solution where you use the srcdoc doc property of the iframe in order to replace the video player with a thumbnail and a link.

This solution is really nice because it doesn't require any additional tooling, you simply have to write a bit more of html.

Sounds perfect? Almost. It has one slight issue: on mobile, you need to tap twice to play the video. When reading the comments, I learned about another possible solution...

lite-youtube custom element

I love custom elements! They are such a clean, self-contained piece of feature. If only they were the default way of using javascript.

What does this custom element provides?

Provide videos with a supercharged focus on visual performance. This custom element renders just like the real thing but approximately 224× faster.

Sounds like a deal. But maybe you don't want to/cannot add easily these files to your project. Or you simply want to test it. This is why I created a really simple service (hosted on Vercel) that is powered by this custom element. Simply replace your regular YouTube embed by this.

<div class="iframe-container">  
<iframe
    src="https://lite-youtube-embed-iframe.vercel.app/embed/ogfYd705cRs?controls=0"
    loading="lazy"></iframe>
</div>

I'm not sure if it's really better than the solution from css-tricks, but using this custom element has some nice side effects, like using youtube-nocookies by default. I just wanted to experiment to see if this could be a viable solution.

So what do you think? Is this better than adding the custom element to your project?

As usual, you can also check the repository or check the demo or even check the app itself.