TLDR Web Dev · ARTICLES & TUTORIALS
FIGHTING WITH YOUTUBE TO SHOW A PREVIEW IMAGE
Summary from the TLDR Web Dev newsletter
A method for displaying YouTube video previews on a webpage efficiently delays the loading of the full video iframe until the user clicks the preview. The standard approach of using YouTube's thumbnail URL can fail because the highest resolution image isn't always available, and YouTube's fallback image triggers the onload event instead of onerror. The solution involves checking the image size in the onload handler to determine if the fallback image is loaded, and then iterating through lower resolution thumbnails until a valid one is found.