jQuery: Check if image exists

后端 未结 6 690
予麋鹿
予麋鹿 2020-11-27 17:20

I\'m loading an image path via jQuery $.ajax and before showing the image I\'d like to check if it in fact exists. Can I use the image load/ready event or something similar

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 18:19

    This is what I did of mine:

    $.get( 'url/image', function(res){ 
        //Sometimes has a redirect to not found url
        //Or just detect first the content result and get the a keyword for 'indexof'
        if ( res.indexOf( 'DOCTYPE' ) !== -1 )  {
            //not exists
        } else {
            //exists
        }
    });
    

提交回复
热议问题