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<insert-youtube-video-id-here>/maxresdefault.jpg

but some videos dont have that so you have to resort to<insert-youtube-video-id-here>/hqdefault.jpg


then finally<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

awarded to ocanal

Crowdsource coding tasks.

1 Solution

Winning solution

Here is my solution,

Live Example

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

$"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) {