sustainable.dev Menu

Posted to Resource on December 28, 2020


Lazy load embedded YouTube videos

Avoid the added bloat, load time, and tracking of embedded YouTube videos until the user interacts with the media.

This seemingly simple trick is actually very clever. It is able to keep most of the look and feel of your YouTube embed whilst saving loads of data and nasty tracking scripts from the Google monolith.

How to lazy load YouTube embeds

The technique utilises srcdoc, a feature of <iframe> that allows you to put the entire contents of an HTML document in the attribute.

Even better, we can now use native browser lazy loading to improve this even further, saving even more bytes on the initial page load as there are no requests to the server if the video isn’t in the viewport.

<iframe
  width="560"
  height="315"
  src="https://www.youtube.com/embed/7V8oFI4GYMY"
  srcdoc="<style>*{padding:0;margin:0;overflow:hidden}html,body{height:100%}img,span{position:absolute;width:100%;top:0;bottom:0;margin:auto;}span{height:2em;text-align:center;font:48px/2 sans-serif;color:white;text-shadow:0 0 0.5em black;}</style><a href='https://www.youtube.com/embed/7V8oFI4GYMY?autoplay=1'><img src='https://img.youtube.com/vi/7V8oFI4GYMY/hqdefault.jpg' alt='Video - What is sustainable development' /><span>▶</span></a>"
  frameborder="0"
  allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
  allowfullscreen
  title="What is sustainable development"
  loading="lazy"
></iframe>

Check out the CodePen example here.

Conclusion

We think this is a great little trick that saves having to load additional scripts, and if you have many embeds on one page, potentially significant reduction in loading times. While it does mean you are still loading an image for the background from YouTube, at least you have a little more control. By adding in loading="lazy" you can save your users from loading that image if the page loads without the embed within the viewport, or at all if they never scroll to it.

It does have its downsides though. One is that it is tricky to style the simple Play button to look like YouTube’s. For some users, this may cause distrust. For others, it could improve trust through the use of a company-branded play icon.

The other obstacle is that users may need to click/tap twice to play the video. This is because some browsers/systems won’t support the addition of autoplay=1 when the user clicks the first time. So, while the YouTube video will load fully on the first click, it may not start to play, causing the extra click needed from the user to play the video. Some would argue that this is a worse user experience, which we can certainly understand. But, if you want to make your website more sustainable and you have many embeds, is one extra click all that bigger deal? Especially on mobile devices where data is at a premium and autoplay is often forced to be off anyway?

 
References: css-tricks.com / dev.to