How to Lazy Load an Embedded Youtube Video

mixanikos365

This is an example of how to display the image thumbnail for a Youtube video and only load the video once the user interacts with the video.


Basic Steps

  • Grab the Youtube ID from the URL of any Youtube video
    Youtube ID in URL


  • The image path for the thumbnail is
    https://i.ytimg.com/vi/{Youtube ID}/maxresdefault.jpg


  • The embed URL for the iframe src is
    https://www.youtube.com/embed/{Youtube ID}?autoplay=1


Typically you would not want to include ?autoplay=1 to autoplay the video because that's annoying af, but in this case, we're loading the video only once the user has already clicked on it to play it


  • Using Javascript, swap out the image container with a responsive video container and the iframe with the embed URL
Credit to this repo for the idea for the play button css.


Tags

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !