Oh, embed! | adactio

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:

  1. Get the URL of the video you want to upload;
  2. Ping the oEmbed endpoint like so: https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=-eiqhVmSPcs
  3. 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)
  4. 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>
  1. Add an onClick event to swap it out with an iframe (tip: use the youtube-nocookie URL for increased user privacy)

Done. Responsive, progressively enhanced, and much more performant. Great tip 👍

Explore Other Notes

⬅ Newer

Let a website be a worry stone

There's a lot to love in Ethan's thoughts. I saw his tweet weeks ago but found myself returning to it time and time again in my mind, what with, well, everything right now. It's great to see […]
  • 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 &lt;iframe&gt; when clicked? Sounds great, but wouldn't [&#8230;]
  • Murray Adcock.
Journal permalink

Made By Me, But Made Possible By:

CMS:

Build: Gatsby

Deployment: GitHub

Hosting: Netlify

Connect With Me:

Twitter Twitter

Instagram Instragram

500px 500px

GitHub GitHub

Keep Up To Date:

All Posts RSS feed.

Articles RSS feed.

Journal RSS feed.

Notes RSS feed.