简体   繁体   中英

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

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.

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/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM