2

is it possible to check the status codes of images using jQuery/JS?

For example,

img1 = "http://upload.wikimedia.org/wikipedia/commons/thumb/2/26/YellowLabradorLooking_new.jpg/260px-YellowLabradorLooking_new.jpg";

if(statusCheck(img1) == 404){
    /do something
}elseif(statusCheck(img1) == 403){
    //do something else
}elseif(statusCheck(img1) == 304){
    //do something else
}

Thanks

2
  • WHEN and HOW you're going to download such image? Commented Jan 9, 2013 at 0:52
  • 1
    You could try accomplish that with XMLHTTPRequest but you have to be aware that most of the sites don't allow crossDomain requests (and for good reasons!) Commented Jan 9, 2013 at 0:56

1 Answer 1

6

You can construct an Image object, which isn't affected by cross-origin restrictions:

var image = new Image();
image.src = "http://upload.wikimedia.org/wikipedia/commons/thumb/2/26/YellowLabradorLooking_new.jpg/260px-YellowLabradorLooking_new.jpg"

image.onload = function() {
    alert('Image has loaded');
};

image.onerror = function() {
    alert('Image did not load');
};

Image loading is asynchronous, so making a function that returns the error code won't be a good idea.

Demo: http://jsfiddle.net/Blender/apyL7/

Also, there doesn't seem to be a way to get the response code, so you're limited to knowing only whether the image loaded or not.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, So you are saying it is not possible to retrieve the http status codes? For example 304 is different than 200 even though they can both load.
What about Flickr images that have been removed, hidden and moved? Flickr doesn't remove them physically, but notifies with 301, that the image has been moved permanently. Try this one: farm9.static.flickr.com/8521/8619601616_b4ba28c3b0_z.jpg (it's broken, but still loaded and 'load' event is fired).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.