JavaScriptで任意のURLに画像が存在するか確認する方法

コード


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が返ってきたりする場合があるのでonloadonerrorを使った方がいいらしい。

参考