Youtube returns 404 for not existing thumbnails, but it also returns valid image data (broken video thumbnail), so checking it with Image does not work, onerror is not called:
var img = new Image();
img.onload = function() { alert("found")};
img.onerror = function() { alert("not found") };
img.src = "http://img.youtube.com/vi/aaaa/1.jpg";
When run then it says "found". Is there a way to detect 404 if the image data can actually be loaded?
It is also good if it shomehow can be detected that the link returns the standard youtube "broken video" thumbnail image data.
To check if an img src is valid: Add an error event listener on the img element. If the src is invalid, set it to a backup image. Alternatively, hide the image.
If you have ever wanted to check whether a page has returned a 404 for any reason, one of the easiest ways is to use this little helper function UrlExists() with the current url, given by window. location. href. This will return a true if the http status is anything except a 404, otherwise it will return false .
As a crude but working workaround in this case I would suggest checking the image's size on load. Usually the thumbnails are bigger, so if the returned image is 120x90px you can assume it's the 404 image.
The only other way will be to have it load via a PHP script that can check the HTTP Headers before passing through the image.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With