Is it possible to check if a file returns a 404 error if it's on a different server using jQuery/javascript?
I'm using the youtube api to get a HD screenshot for the video I'm embedding, but the JSON that it returns gives no indication of whether a HD screenshot for the video exists.
the url for the screenshot is usually, / + video.ID + /maxresdefault.jpg
but when it doesn't exist, i get this ugly low-res gray POS: .jpg
So, basically, I want to check if the screenshot exists and if not, apply display: none
to the div that holds it.
Is it possible to check if a file returns a 404 error if it's on a different server using jQuery/javascript?
I'm using the youtube api to get a HD screenshot for the video I'm embedding, but the JSON that it returns gives no indication of whether a HD screenshot for the video exists.
the url for the screenshot is usually, http://img.youtube.com/vi/ + video.ID + /maxresdefault.jpg
but when it doesn't exist, i get this ugly low-res gray POS: http://img.youtube.com/vi/MAyTES9gDAU/maxresdefault.jpg
So, basically, I want to check if the screenshot exists and if not, apply display: none
to the div that holds it.
5 Answers
Reset to default 5Create an <img>
element pointing to that image, then handle the onerror
event and hide it.
You can create an Image
object and handle onload
and onerror
. It'll only work for images, mind.
function checkExists(imageUrl, callback) {
var img = new Image();
img.onerror = function() {
callback(false);
};
img.onload = function() {
callback(true);
};
img.src = imageUrl;
}
Use it like this:
checkExists(yourVideoUrl, function(exists) {
if(!exists) {
// Hide the image
}
});
Here's a demo.
minitech's answer works for checking 404's, however...
For the YouTube case, they have their own handling instead of giving you a 404, they give you a "nice" error image.
YouTube has an API that will check if the video ID is valid. Check out this post that tells you how to check if a YouTube video id exists or is valid: https://groups.google.com/forum/?fromgroups=#!topic/youtube-api-gdata/oAztQ3f1tcM
Once you confirm that the video exists, you can then try to load up the image. If the video doesn't exist, you can handle that case however you want.
This worked for me (mine is in coffeescript).
checkImages = ->
$("img").each ->
$(this).error ->
$(this).attr("src", "../default/image.jpg")
$(document).on('page:load', checkImages)
I'm guessing the javascript equivalent is something like
function checkImages() {
$("img").each(function() {
$(this).error(function() {
$(this).attr("src", "../default/image.jpg");
});
});
};
$(document).on("page:load", checkImages);
You have to add extra check for a default gray image:
function checkExists(imageUrl, callback) {
var img = new Image();
img.onerror = function() {
callback(false);
};
img.onload = function() {
//check for a default (grey) image
if (this.width == 120) {
callback(false);
}else {
callback(true);
}
};
img.src = imageUrl;
}
Demo