Lazy load embedded YouTube videos


0

I was working on this simple static website that should have an YouTube video displayed right on the landing page. So I went my merry way, hopped onto YouTube, snatched the embed code, pasted it into my editor and called it a day.

YouTube share dialog

The thing is the job was specifically to deliver high performance, accessibility and modern practices, so you can imagine my annoyance when I noticed that just for having this

So I thought what if instead of the actual video I showed just its cover linked to the video? It would still kinda look like an embedded video but it would require only a single image upfront. Thankfully YouTube has an URL schema for video thumbnails.

 href="https://www.youtube.com/embed/Y8Wp3dafaMQ">
   src="https://i3.ytimg.com/vi/Y8Wp3dafaMQ/hqdefault.jpg">

Cool, but I really don’t want to have to create a whole new page just for this teeny tiny snippet of code. Well, we’re in luck cause

Finally you’ll notice that if we click the image it’ll load the video but in a paused state and we would need to click it again to start watching. Fret not, cause the embed video URL supports player parameters and among those there’s the autoplay variable which does exactly what you would expect. Additionally due to browser’s default style users on systems with scrollbar—namely not macOS—will see an unnecessary scrollbar, but nothing that a small CSS reset wouldn’t fix.

Remy Sharp pointed out we should keep the src as fallback to browsers that don’t support srcdoc. Adrian Roselli suggested a few tweaks to improve accessibility. Also, while applying these suggestions I fixed the image position so it stays centered both horizontally and vertically without resorting to background-size: cover. Thank you guys for your feedback! 🤩️

Here’s the final result:

The

This way all the users will have to download upfront is the cover image, which seems pretty reasonable to me. You can customize it further, e.g. make use of the different thumbnail sizes for different devices, and if you need more control over what the user will load and what features to enable you can always explore the YouTube Player API.

If you’ve got any questions, corrections or suggestions feel free to comment below. Thank you for your time. 😊️


Like it? Share with your friends!

0
admin

Choose A Format
Personality quiz
Series of questions that intends to reveal something about the personality
Trivia quiz
Series of questions with right and wrong answers that intends to check knowledge
Poll
Voting to make decisions or determine opinions
Story
Formatted Text with Embeds and Visuals
List
The Classic Internet Listicles
Countdown
The Classic Internet Countdowns
Open List
Submit your own item and vote up for the best submission
Ranked List
Upvote or downvote to decide the best list item
Meme
Upload your own images to make custom memes
Video
Youtube, Vimeo or Vine Embeds
Audio
Soundcloud or Mixcloud Embeds
Image
Photo or GIF
Gif
GIF format