How to tell if dynamically loaded image exists

痴心易碎 提交于 2019-12-06 14:52:02

using jquery you can do it this way:

<img src="http://myimages.com/image.jpg" id="imgId" />

$('#imgId').load(function(){
 // ... loaded  
}).error(function(){
 // ... not loaded
 $(this).attr('src','/whatever/default.png');
});

I would just try loading the images, and if you get an error, fall back to a default:

$('img').error(function()
{
  $(this).attr('src', '/whatever/default.png');
});

EDIT: This solution might not work, so I'll supply you with an alternate one. When an image doesn't load, it theoretically has a width of 0 (assuming you didn't style the <img> tags). This code might work:

$('img').each(function()
{
  if ($(this).width() == '0px')
  {
    $(this).attr('src', '/whatever/default.png');
  }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!