Check if image exists on server using JavaScript?

前端 未结 12 742
抹茶落季
抹茶落季 2020-11-22 06:24

Using javascript is there a way to tell if a resource is available on the server? For instance I have images 1.jpg - 5.jpg loaded into the html page. I\'d like to call a Jav

相关标签:
12条回答
  • 2020-11-22 07:05

    You can just check if the image loads or not by using the built in events that is provided for all images.

    The onload and onerror events will tell you if the image loaded successfully or if an error occured :

    var image = new Image();
    
    image.onload = function() {
        // image exists and is loaded
        document.body.appendChild(image);
    }
    image.onerror = function() {
        // image did not load
    
        var err = new Image();
        err.src = '/error.png';
    
        document.body.appendChild(err);
    }
    
    image.src = "../imgs/6.jpg";
    
    0 讨论(0)
  • 2020-11-22 07:09

    You could use something like:

    function imageExists(image_url){
    
        var http = new XMLHttpRequest();
    
        http.open('HEAD', image_url, false);
        http.send();
    
        return http.status != 404;
    
    }
    

    Obviously you could use jQuery/similar to perform your HTTP request.

    $.get(image_url)
        .done(function() { 
            // Do something now you know the image exists.
    
        }).fail(function() { 
            // Image doesn't exist - do something else.
    
        })
    
    0 讨论(0)
  • 2020-11-22 07:10

    A better and modern approach is to use ES6 Fetch API to check if an image exists or not:

    fetch('https://via.placeholder.com/150', { method: 'HEAD' })
        .then(res => {
            if (res.ok) {
                console.log('Image exists.');
            } else {
                console.log('Image does not exist.');
            }
        }).catch(err => console.log('Error:', err));
    

    Make sure you are either making the same-origin requests or CORS is enabled on the server.

    0 讨论(0)
  • 2020-11-22 07:11

    If you create an image tag and add it to the DOM, either its onload or onerror event should fire. If onerror fires, the image doesn't exist on the server.

    0 讨论(0)
  • 2020-11-22 07:14

    If you are using React try this custom Image component:

    import React, { useRef } from 'react';
    import PropTypes from 'prop-types';
    
    import defaultErrorImage from 'assets/images/default-placeholder-image.png';
    
    const Image = ({ src, alt, className, onErrorImage }) => {
      const imageEl = useRef(null);
      return (
        <img
          src={src}
          alt={alt}
          className={className}
          onError={() => {
            imageEl.current.src = onErrorImage;
          }}
          ref={imageEl}
        />
      );
    };
    
    Image.defaultProps = {
      onErrorImage: defaultErrorImage,
    };
    
    Image.propTypes = {
      src: PropTypes.string.isRequired,
      alt: PropTypes.string.isRequired,
      className: PropTypes.string.isRequired,
      onErrorImage: PropTypes.string,
    };
    
    export default Image;
    
    0 讨论(0)
  • 2020-11-22 07:15

    If anyone comes to this page looking to do this in a React-based client, you can do something like the below, which was an answer original provided by Sophia Alpert of the React team here

    getInitialState: function(event) {
        return {image: "http://example.com/primary_image.jpg"};
    },
    handleError: function(event) {
        this.setState({image: "http://example.com/failover_image.jpg"});
    },
    render: function() {
        return (
            <img onError={this.handleError} src={src} />;
        );
    }
    
    0 讨论(0)
提交回复
热议问题