The general strategy is to use an DOM Image
object instance, set the src
property to the URL of the image you want to check (which will cause the browser to fetch and load the image), and then handle the load
and error
events to determine existence or absence, respectively.
Here’s an example promise-based approach:
function imageExists(url) {
return new Promise(resolve => {
var img = new Image()
img.addEventListener('load', () => resolve(true))
img.addEventListener('error', () => resolve(false))
img.src = url
})
}
const url="http://www.google.com/images/srpr/nav_logo14.png"
imageExists(url)
.then(ok => console.log(`RESULT: exists=${ok}`))
// => RESULT: exists=true