0xhughes 0xhughes - 7 months ago 70
Javascript Question

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!


You could use something like:

function imageExists(image_url){

    var http = new XMLHttpRequest();

    http.open('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.