Check if image exists on server using JavaScript?

Check if image exists on server using JavaScript?

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!


Solution 1:

You could use something like:

function imageExists(image_url){

    var http = new XMLHttpRequest();'HEAD', image_url, false);

    return http.status != 404;


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

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

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


Solution 2:

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"); } );


Solution 3:

You can just check if the image loads or not by using the built in events that is provided for all images.

The onload and onerror events will tell you if the image loaded successfully or if an error occured :

var image = new Image();

image.onload = function() {
    // image exists and is loaded
image.onerror = function() {
    // image did not load

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


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

Solution 4:

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 Sophia Alpert of the React team here

getInitialState: function(event) {
    return {image: ""};
handleError: function(event) {
    this.setState({image: ""});
render: function() {
    return (
        <img onError={this.handleError} src={src} />;

Solution 5:

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.

Solution 6:

This works fine:

function checkImage(imageSrc) {
    var img = new Image();        
    try {
        img.src = imageSrc;
        return true;
    } catch(err) {
        return false;