Home >Web Front-end >JS Tutorial >How to Check if an Image Exists on the Server with JavaScript?
Question:
How to programmatically determine if an image resource exists on the server using JavaScript?
Answer:
Utilizing JavaScript, you can check image availability by initiating an HTTP request using XMLHttpRequest or leveraging a library like jQuery.
Consider the following solution using XMLHttpRequest:
function imageExists(image_url) { const http = new XMLHttpRequest(); http.open('HEAD', image_url, false); http.send(); return http.status != 404; }
This function sends an HTTP HEAD request to the specified image URL and checks if the response status is not 404 (not found). If the image exists, it returns true; otherwise, it returns false.
Alternatively, you can use jQuery for a concise implementation:
$.get(image_url) .done(function() { // Image exists - take appropriate action. }) .fail(function() { // Image doesn't exist - handle accordingly. });
Using these techniques, you can dynamically check for image availability and modify your HTML accordingly.
The above is the detailed content of How to Check if an Image Exists on the Server with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!