Check if image exists on server using JavaScript?

前端 未结 12 735
抹茶落季
抹茶落季 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:27

    You may call this JS function to check if file exists on the Server:

    function doesFileExist(urlToFile)
    {
        var xhr = new XMLHttpRequest();
        xhr.open('HEAD', urlToFile, false);
        xhr.send();
    
        if (xhr.status == "404") {
            console.log("File doesn't exist");
            return false;
        } else {
            console.log("File exists");
            return true;
        }
    }
    

提交回复
热议问题