Home >Web Front-end >JS Tutorial >How to Check if an Image Exists on a Server with JavaScript?

How to Check if an Image Exists on a Server with JavaScript?

DDD
DDDOriginal
2024-11-16 15:19:03627browse

How to Check if an Image Exists on a Server with JavaScript?

How to Verify Image Existence on Server with JavaScript

Checking if a resource exists on a server is crucial in many web applications, such as dynamically loading images. Let's explore how to accomplish this using JavaScript.

Problem:

You have multiple images (e.g., 1.jpg to 5.jpg) embedded in your HTML page and want to periodically check if an additional image (e.g., 6.jpg) is available on the server. To achieve this, you need to call a JavaScript function every minute to perform the following checks:

if "../imgs/6.jpg" exists:
    var nImg = document.createElement("img6");
    nImg.src = "../imgs/6.jpg";

Solution:

To check if an image exists on the server, you can utilize the following JavaScript code:

function imageExists(image_url){

    var http = new XMLHttpRequest();

    http.open('HEAD', image_url, false);
    http.send();

    return http.status != 404;

}

Explanation:

This code snippet employs the XMLHttpRequest object to send an HTTP HEAD request to the specified image URL. The HEAD request returns the HTTP status code associated with the resource, indicating whether it exists. A status code of 200 or 304 indicates that the resource exists, while a 404 status code signifies its absence.

Alternatively, you can use a jQuery implementation:

$.get(image_url)
    .done(function() { 
        // Do something now you know the image exists.

    }).fail(function() { 
        // Image doesn't exist - do something else.

    })

This jQuery approach also performs an HTTP GET request and executes the specified callbacks based on the server's response.

The above is the detailed content of How to Check if an Image Exists on a Server with 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