Home  >  Article  >  Web Front-end  >  How Can I Check if an Image Exists on a Server Using JavaScript?

How Can I Check if an Image Exists on a Server Using JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-19 08:48:02965browse

How Can I Check if an Image Exists on a Server Using JavaScript?

Detecting Image Availability on Server with 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.

Solution:

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

Example:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn