StronglyTyped
StronglyTyped

Reputation: 2134

How to tell if dynamically loaded image exists

I'm dynamically loading images from a different website into an asp.net ListView control like this:

<ListView>
   <ItemTemplate>
      <img src='<%# string.Format("http://www.Website.com/Images/{0}", Eval("ImageName")) %>' />

Sometimes, the images don't exist and I need to change the src to a static path: src="/whatever/default.png". What is the fastest way I check if the image exists and update the src if it doesn't (any client side possibilities via jQuery)? The ListView is paged and could contain a result set of thousands of records, so I'd only like to check the images that are on the current page to optimize performance. Thanks!

Upvotes: 1

Views: 3386

Answers (2)

Blender
Blender

Reputation: 298206

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');
  }
});

Upvotes: 0

ezmilhouse
ezmilhouse

Reputation: 9121

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');
});

Upvotes: 2

Related Questions