Search code examples
javascriptjqueryajaxxmlhttprequestloading

Check if image exists without loading it


I am currently using following script in a hover-functionality:

function UrlExists(url) {
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}

It loads every image each after the other, causing to slow down the entire website (or even crashing).

Is there a way to check if an image exists, though prevent loading it (fully) using javascript?

Thanks alot!


Solution

  • Since JavaScript (and therefore jQuery) is client-side and the image resides server-side before loading there is no way to check to see if the image exists without using Ajax or your server-side scripting to make sure the image exists.