user1937021
user1937021

Reputation: 10791

detect if image URL is broken or not JQUERY

Is there a way to detect if an image URL is broken or not from its URL, say I want to check if this image loads:

http://www.domain.com/img/slide1.jpg

From the URL solely, not from the html code

Thanks

Upvotes: 1

Views: 2478

Answers (3)

riv
riv

Reputation: 7323

Use the onerror handler. However, it must be attached before the error is triggered, so you want to set the src property afterwards:

$("img").error(function(){
  $(this).hide();
}).attr('src', 'http://www.domain.com/img/slide1.jpg');

https://api.jquery.com/error/

Upvotes: 1

rfornal
rfornal

Reputation: 5122

I've seen this as an option ...

<img src="foo.jpg" onerror="if (this.src != 'error.jpg') this.src = 'error.jpg';">

This could also fire a function.

You could also try something like this ...

<object data="http://stackoverflow.com/does-not-exist.png" type="image/png">
  <img src="http://stackoverflow.com/content/img/so/logo.png" />
</object>

Since the first image doesn't exist, the fallback (the Stack Overflow logo) will display. And if you're using a really old browser that doesn't support object, it will just ignore that tag and use the img tag.

UPDATE:

Using image path (URL), try something like this ...

http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

Pre-loading via ajax might give an answer, then you can use Success/Error handling.

Upvotes: 0

Yurii Kovalenko
Yurii Kovalenko

Reputation: 419

For check is the current URL available you can use HEAD HTTP request (that does not load request body). It describes in this HTTP HEAD Request in Javascript/Ajax? question.

Upvotes: 1

Related Questions