0

I have a image URL (http://t2.gstatic.com/images?q=tbn:ANd9GcTR_RHZrrb25Cx1qGPul6PYsCnVsIqtRuJxRS1Bj0I8DPXqQx-zow). I want to validate this in JavaScript whether image exists or not. Please help me in finding the solution.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
vignesh
  • 1,573
  • 7
  • 33
  • 60
  • possible duplicate of [How do I check if file exists in jQuery or Javascript?](http://stackoverflow.com/questions/3646914/how-do-i-check-if-file-exists-in-jquery-or-javascript) – Curtis Mar 06 '12 at 10:05

3 Answers3

2
try {
var img = document.createElement("img");
img.src ="http://t2.gstatic.com/images?q=tbn:ANd9GcTR_RHZrrb25Cx1qGPul6PYsCnVsIqtRuJxRS1Bj0I8DPXqQx-zowsd";

} catch(err)
{
    //
}

if(img.height > 0) {
 //image exists
} else {
 // image not exists
}
user160820
  • 14,866
  • 22
  • 67
  • 94
1

You can load your image in an hidden DIV and check if the image was loaded. I suggest you to use jQuery to achieve this.

Further reading on the load Event: http://api.jquery.com/load-event/

HTML:

<div id="image-container" style="display: none">
    <img src="http://your/image/url">
</div>

Javascript / jQuery Code:

    $('img', '#image-container ').load(function() {
        // image loaded
    });
Julian Hollmann
  • 2,902
  • 2
  • 25
  • 44
0

Your post is almost same as Change image source if file exists which was previously posted by anothershrubery.

You can try this

<img src="http://mydomain.com/images/image1.jpg" onerror="this.src='http://mydomain2.com/images/image1.jpg'" />

Alternatively

<script language="JavaScript"><!-
function testImage(URL) {
var tester=new Image();
tester.onLoad=isGood;
tester.onError=isBad;
tester.src=URL;
}

function isGood() {
alert('That image exists!');
}

function isBad() {
alert('That image does no exist!');
}
//--></script>
Community
  • 1
  • 1
Anoop Pete
  • 492
  • 2
  • 4
  • 17