js怎样判断图片链接是否有效

2020-08-09  本文已影响0人  极客开发者
function checkImgExists(imgurl) {
    return new Promise(function(resolve, reject) {
      var ImgObj = new Image()
      ImgObj.src = imgurl
      ImgObj.onload = function(res) {
        resolve(res)
      }
      ImgObj.onerror = function(err) {
        reject(err)
      }
    })
}
checkImgExists('https://test.com/dssd=0.jpg').then(()=>{
    //success callback
    console.log('有效链接')
}).catch(()=>{
    //fail callback
    console.log('无效链接')
})

全部代码如下:

function checkImgExists(imgurl) {
    return new Promise(function(resolve, reject) {
      var ImgObj = new Image();
      ImgObj.src = imgurl;
      ImgObj.onload = function(res) {
        resolve(res);
      }
      ImgObj.onerror = function(err) {
        reject(err)
      }
    })
}

checkImgExists('https://test.com/20200803115749u=2876792700,1627849181&fm=26&gp=0.jpg').then(()=>{
    //success callback
    console.log('有效链接')
}).catch(()=>{
    //fail callback
    console.log('无效链接')
})
上一篇下一篇

猜你喜欢

热点阅读