Check if image exists on server using JavaScript?

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

提交回复
热议问题