Check if image exists on server using JavaScript?

前端 未结 12 943
抹茶落季
抹茶落季 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";
    

提交回复
热议问题