Checking If Image Does Exists Using JavaScript

Check if image exists on server using JavaScript?

You could use something like:

function imageExists(image_url){

var http = new XMLHttpRequest();

http.open('HEAD', image_url, false);
http.send();

return http.status != 404;

}

Obviously you could use jQuery/similar to perform your HTTP request.

$.get(image_url)
.done(function() {
// Do something now you know the image exists.

}).fail(function() {
// Image doesn't exist - do something else.

})

Check if image exists before loading

The problem it does not work is getThumbnail() method will not behave as you want.

The .onload is an async call and for this case, getThumbnail(value) will always have undefined returned result;

To accomplish what you want, you can do something like:

<img src="/image/..." onerror="javascript:this.src='images/default.jpg'"/>

Checking if image does exists using javascript

The general strategy is to use an DOM Image object instance, set the src property to the URL of the image you want to check (which will cause the browser to fetch and load the image), and then handle the load and error events to determine existence or absence, respectively.

Here's an example promise-based approach:

function imageExists(url) {
return new Promise(resolve => {
var img = new Image()
img.addEventListener('load', () => resolve(true))
img.addEventListener('error', () => resolve(false))
img.src = url
})
}

const url = 'http://www.google.com/images/srpr/nav_logo14.png'
imageExists(url)
.then(ok => console.log(`RESULT: exists=${ok}`))
// => RESULT: exists=true

see if src of img exists

You can use the error event:

var im = document.getElementById('imageID'); // or select based on classes
im.onerror = function(){
// image not found or change src like this as default image:

im.src = 'new path';
};

Inline Version:

<img src="whatever" onError="this.src = 'new default path'" />

Or

<img src="whatever" onError="doSomething();" />

<img> tag supports these events:

  • abort (onAbort)
  • error (onError)
  • load (onLoad)

More Information:

  • JavaScript Events
  • jQuery's error

Check if an image is present

You can check the .length of the image element:

if($('#holder > .holderClass').length > 0) {
//Exists!
}

If you want to check for a specific image, check the src attribute:

if($('#holder > .holderClass[src="path/to/img.png"]').length > 0) {
//Exists!
}

How to check if image exists?

This is probably the shortest possible code to handle lost images in JS. imagePad is a reference to the DOM element in which you want to show the image.

var img = new Image();
img.addEventListener('error', function (e) {
// Image not found, show the default
this.src = iconBase + 'gen.png';
});
img.addEventListener('load', function () {
imagePad.appendChild(img);
}
img.src = 'the_given_src';

Test if a photo exists Javascript

Among other things, you need an event handler to execute the test.

<script>
var photosArray = ["1.jpg", "2.jpg", "3.jpg", "4.jpg"];
var src = photosArray[4] + '?v=' + new Date().getTime(); // photosArray[5] doesn't exist because arrays are 0-indexed

console.log('src: ' + src);

function imageExists(src){
var http = new XMLHttpRequest();
var exists;

http.open('GET', src, true);

http.onreadystatechange = function(){
if (http.readyState === 4 && http.status >= 200 && http.status < 300) {
console.log('okay');
exists = true;
// do something
}
else {
console.log('fail');
exists = false;
// do something
}
// do something, perhaps foo(exists);
}

http.send();

}

imageExists(src);
</script>

You can't simply return the value for exists from this function however, because XMLHttpRequest, as you noted, is asynchronous: imageExists() will return before the XMLHttpRequest has finished, and you'll get false negatives. Returning the event handler will not return a value for imageExists either, only for the event handler function. The best you can do is do something when the XMLHttpRequest's onreadystatechange (or, in modern browsers, onload) event fires.

You should look into Promises, the fetch API, or create a variable in the parent scope (updating it from the event handler) and check it at intervals, in order to ascertain whether the image exists.

Alternatively, use window.setTimeout with a variable in parent scope and check that variable after 'a reasonable amount of time' -- hint: judging what a reasonable amount of time should be is not a simple matter, given the almost impossible task of measuring the client's internet connection speed or deducing any kind of deterministically reliable estimate for 'a reasonable amount of time' for images of varying sizes.

Also, be aware that requesting an image may not give you a reliable result, as images can be cached by the browser. Hence why I append a cache-busting string to src with '?v=' + new Date().getTime();

What you can do is attach event handlers on the image itself, like this:

<img src="/path/to/whatever.jpg" onerror="this.style.display='none'">

or

<style>img.not-loaded { display: none; }</style>
<img src="/path/to/whatever.jpg" class="not-loaded" onload="this.className=''">

Either of which would serve to hide the image if it wasn't found or if the request for it otherwise failed.

Edit: based on your comments, this is how you might go about it:

window.imageExists = function(main_img){    main_img.className+=' loaded';    [].slice.call(main_img.parentNode.querySelectorAll('.secondary-image')).forEach(function(this_img){      this_img.src = this_img.getAttribute('data-src');    });  };
  img { display: none; }  img.loaded { display: block; width: 100%; }  img.secondary-image.loaded { display: inline-block; width: 20%; }  
<div class="main-image-container">  <img src="http://i.imgur.com/VwQjLZI.jpg" class="main-image" onload="imageExists(this)">  <img src="" data-src="http://i.imgur.com/VwQjLZI.jpg" class="secondary-image" onload="this.className+=' loaded';">  <img src="" data-src="http://i.imgur.com/VwQjLZI.jpg" class="secondary-image" onload="this.className+=' loaded';">  <img src="" data-src="http://google.com/does_not_exist.jpg" class="secondary-image" onload="this.className+=' loaded';">  <img src="" data-src="http://i.imgur.com/VwQjLZI.jpg" class="secondary-image" onload="this.className+=' loaded';"></div>


Related Topics



Leave a reply



Submit