Check if image exists on server using JavaScript?

前端 未结 12 875
抹茶落季
抹茶落季 2020-11-22 06:24

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 Jav

12条回答
  •  没有蜡笔的小新
    2020-11-22 07:09

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

提交回复
热议问题