YouTube embeds can be expensive on page load metrics, but what alternative is there? How about loading a thumbnail that hot-swaps itself for an <iframe> when clicked? Sounds great, but wouldn't that mean you have to create custom thumbnails for each video? Nope, YouTube has a bunch of weird and wonderful hidden features in its API that will give you everything you need:
- Get the URL of the video you want to upload;
- Ping the
oEmbedendpoint like so:https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=-eiqhVmSPcs - Pull out the thumbnail URL from the returned JSON (quick tip: you can actually skip the first two steps and just use the ID for this instead)
- Add it to some markup:
<a class="videoimglink" href="'.$url.'">
<img width="100%" loading="lazy"
src="https://i.ytimg.com/vi/'.$id.'/default.jpg"
alt="'.$response['title'].'"
srcset="
https://i.ytimg.com/vi/'.$id.'/mqdefault.jpg 320w,
https://i.ytimg.com/vi/'.$id.'/hqdefault.jpg 480w,
https://i.ytimg.com/vi/'.$id.'/maxresdefault.jpg 1280w
">
</a>
- Add an
onClickevent to swap it out with aniframe(tip: use theyoutube-nocookieURL for increased user privacy)
Done. Responsive, progressively enhanced, and much more performant. Great tip 👍
