Home > Web Front-end > JS Tutorial > body text

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

Mary-Kate Olsen
Release: 2024-11-19 08:48:02
Original
952 people have browsed it

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;
}
Copy after login

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.
  })
Copy after login

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";
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template