コード
const checkIfImageExists = (url) => {
return new Promise((resolve, reject) => {
const img = new Image();
img.src = url;
img.onload = () => resolve(url);
img.onerror = () => reject(url);
});
};
checkIfImageExists('https://placehold.jp/150x150.png')
.then((url) => {
console.log(`Image found: ${url}`);
})
.catch((url) => {
console.log(`Image not found: ${url}`);
});
fetch
でやる方法もあるが、画像が存在しない場合でも200が返ってきたりする場合があるのでonload
、onerror
を使った方がいいらしい。