Categories
javascript

Check if image exists on server using JavaScript?

153

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 "https://stackoverflow.com/questions/18837735/imgs/6.jpg" exists:
    var nImg = document.createElement("img6");
    nImg.src = "https://stackoverflow.com/questions/18837735/imgs/6.jpg";

Thoughts? Thanks!

    247

    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.
    
        })
    

    14

    • 6

      But shouldn’t function name be fileExists because this works on .js .css .html or any other publicly available file.

      – CoR

      Jun 11, 2015 at 14:56

    • 1

      Function is awesome. I put it in my collection 🙂 I thought fileExists would be better name because this function does not check if image exists on server. It check if file is accessible from server. There is no check if that file actually is an image. It could be .pdf, .html, some random file renamed to *.jpg or *.png. If something ends with .jpg it doesn’t mean it’s 100% image 🙂

      – CoR

      Jun 16, 2015 at 9:53

    • 10

      This will fail unless accessing the resource is permitted under CORS rules. Using an Image object doesn’t suffer that limitation. The only advantage of this is that it won’t actually download the image.

      – Alnitak

      Jul 13, 2016 at 18:28


    • 8

      cross-domain issue.

      Aug 25, 2016 at 10:41

    • 2

      This does work, but keep in mind that it takes longer to process the request and isn’t the best solution. Also it doesn’t work on cross origin (definitely in chrome) so you can’t use it on file:/// protocol which means no local usage.

      – Cameron

      May 20, 2017 at 22:40

    151

    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

    7

    • Hey, cool function! As a side note, this is an interesting way of returning the results, direct into an anonymous function. I would normally do this with a return statement like @ajtrichards has in the first part of his answer.

      Jan 18, 2017 at 20:44

    • Absolutely; but I never really thought about the other way being synchronous. I am coming from a long history of procedural coding, and sometimes miss the “other” way of looking at things… I’ll bet I’m not the only one. 😉

      Jan 18, 2017 at 22:03

    • 3

      For future googlers having a problem this solution, try moving the img.src definition to immediately after the new Image line.

      – Gavin

      Jul 26, 2017 at 8:36

    • 1

      This will not help catching 404 errors if image server returns 404 with actual image content, as e.g. Youtube thumbnail service does: i3.ytimg.com/vi/vGc4mg5pul4/maxresdefault.jpg

      – gvlasov

      Sep 15, 2020 at 19:53


    • @gvlasov so if that is the case, you have to do the head request and look at the response. One option of many from a question back in 2013…

      Sep 15, 2020 at 20:07

    66

    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
        document.body.appendChild(image);
    }
    image.onerror = function() {
        // image did not load
    
        var err = new Image();
        err.src="https://stackoverflow.com/error.png";
    
        document.body.appendChild(err);
    }
    
    image.src = "https://stackoverflow.com/questions/18837735/imgs/6.jpg";
    

    5

    • 2

      The best answer for me, as it works in every case (connexion problem, external server…) +1

      – Reign.85

      Sep 30, 2014 at 17:18

    • 3

      Compared the performance of this answer with the AJAX.get alternative. This answer performs much faster!

      – Samuel

      Feb 16, 2016 at 19:38

    • I like this solution, anyhow it introduces events in both cases (asynchronous execution), which can cause problems in some situations: I would suggest to append the image in any case and then substitute it only in the case of errors.

      Jan 31, 2018 at 11:01

    • @adeno, Does it work when Status Code: 404 Not Found

      – Mahi

      Mar 11, 2019 at 8:03

    • @Mahi – The status code shouldn’t matter, as long as the 404 page doesn’t actually return a valid image, it will fail and trigger the error handler.

      – adeneo

      Mar 21, 2019 at 22:39