Check if image exists on server using JavaScript?

By | December 28, 2017
Questions:

Using javascript is there a way to tell if a resource is available on the server? For instance I have images 1.jpg – 5.jpg loaded into the html page. I’d like to call a JavaScript function every minute or so that would roughly do the following scratch code…

if "../imgs/6.jpg" exists:
    var nImg = document.createElement("img6");
    nImg.src = "../imgs/6.jpg";

Thoughts? Thanks!

Answers:

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.

    })

Questions:
Answers:

You can use the basic way image preloaders work to test if an image exists.

function checkImage(imageSrc, good, bad) {
    var img = new Image();
    img.onload = good; 
    img.onerror = bad;
    img.src = imageSrc;
}

checkImage("foo.gif", function(){ alert("good"); }, function(){ alert("bad"); } );

JSFiddle

Questions:
Answers:

You can just check if the image loads or not:

var image = new Image();

image.onload = function() {
    // image exists and is loaded
    document.body.appendChild(image);
}
image.onerror = function() {
    // image did not load

    var err = new Image();
    err.src = '/error.png';

    document.body.appendChild(err);
}

image.src = "../imgs/6.jpg";

Questions:
Answers:

If anyone comes to this page looking to do this in a React-based client, you can do something like the below, which was an answer original provided by Ben Alpert of the React team here

getInitialState: function(event) {
    return {image: "http://example.com/primary_image.jpg"};
},
handleError: function(event) {
    this.setState({image: "http://example.com/failover_image.jpg"});
},
render: function() {
    return (
        <img onError={this.handleError} src={src} />;
    );
}

Questions:
Answers:

If you create an image tag and add it to the DOM, either its onload or onerror event should fire. If onerror fires, the image doesn’t exist on the server.

Questions:
Answers:

You may call this JS function to check if file exists on the Server:

function doesFileExist(urlToFile)
{
    var xhr = new XMLHttpRequest();
    xhr.open('HEAD', urlToFile, false);
    xhr.send();

    if (xhr.status == "404") {
        console.log("File doesn't exist");
        return false;
    } else {
        console.log("File exists");
        return true;
    }
}

Questions:
Answers:
$("img").on("load",function(){
  alert(" Image Exists...!");
 }).on("error", function(){
   alert("ERROR");
});

Demo: @ http://jsfiddle.net/Ns5mU/304/

Leave a Reply

Your email address will not be published. Required fields are marked *