Catch image error from youtube and rewrite to find correct image
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

so it seems youtube has a thumbnail image which we largely assume to be something like this

http://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg

but some videos dont have that so you have to resort to

http://img.youtube.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg

and

http://img.youtube.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg

then finally

http://img.youtube.com/vi/<insert-youtube-video-id-here>/sddefault.jpg

so what we would like to get is some js that will do two things.

1- if image on the page fails (might be more than 1) have js go through the above cascade of retries until the best first one works. I think we can leverage something like img onerror= if it cant find anything that works then we can show some placeholder image.

2- we need to resolve some meta og tags that might have been using that image for the share image. in this case we would simply search for that exact image url in the page and rewrite it to the right YT image that finally worked.

note: i think your script should only attempt to run on the images that have maxresdefault.jpg this way the scope of the script doesnt expand to non youtube images by accident.

generally looking to automate some of the issue reported here https://stackoverflow.com/questions/34763547/youtube-maxresdefault-thumbnails

awarded to ocanal
Tags
javascript

Crowdsource coding tasks.

1 Solution

Winning solution

Here is my solution,

Live Example

var $youtubeImages = $('img[src*="img.youtube.com"]');

$youtubeImages.one("load", function() { 
   var height = $(this).prop('naturalHeight');
   var src = $(this).attr('src');
   if (height <= 90) {
        if (/maxresdefault/.test(src)) {
            src = src.replace('maxresdefault', 'hqdefault');
      } else if (/hqdefault/.test(src)) {
            src = src.replace('hqdefault', 'mqdefault');
      } else if (/mqdefault/.test(src)) {
            src = src.replace('mqdefault', 'sddefault');
      }
      $(this).attr('src', src);
   }
}).each(function() {
  if(this.complete) {
      $(this).trigger('load');
  }
});