1

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

user1937021
  • 10,151
  • 22
  • 81
  • 143

3 Answers3

1

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.

Community
  • 1
  • 1
Yurii Kovalenko
  • 419
  • 3
  • 10
1

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/

riv
  • 6,846
  • 2
  • 34
  • 63
  • From their documentation: The event handler must be attached before the browser fires the error event, which is why the example sets the src attribute after attaching the handler. Also, the error event may not be correctly fired when the page is served locally; error relies on HTTP status codes and will generally not be triggered if the URL uses the file: protocol. – rfornal Apr 02 '15 at 15:24
  • Actually, it seems to work for me in chrome when used for local files. – riv Apr 02 '15 at 15:29
  • I just posted the documentation to make the answer complete. Some browsers have issues like these, others do not (Chrome seems to do well more often than not). – rfornal Apr 02 '15 at 15:31
0

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.

rfornal
  • 5,072
  • 5
  • 30
  • 42