Home > Article > Web Front-end > How Can I Check if an Image Exists on a Server Using JavaScript?
It is often necessary to verify the existence of a resource, such as an image, on a server. In this article, we will explore how to check if an image exists on a server using JavaScript.
To determine if an image is present on the server, we can leverage JavaScript's XMLHttpRequest (XHR) object to send a HEAD request. The HEAD request retrieves the HTTP headers for a specified resource without downloading the actual content. If the HTTP status code is not 404 (not found), it indicates that the image exists on the server.
One way to implement this solution is:
function imageExists(image_url) { var http = new XMLHttpRequest(); http.open('HEAD', image_url, false); http.send(); return http.status != 404; }
Using jQuery, you can simplify the solution:
$.get(image_url) .done(function() { // Do something now you know the image exists. }) .fail(function() { // Image doesn't exist - do something else. })
To use this method, you can replace your scratch code with:
if (imageExists("../imgs/6.jpg")) { var nImg = document.createElement("img6"); nImg.src = "../imgs/6.jpg"; }
The above is the detailed content of How Can I Check if an Image Exists on a Server Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!