Search code examples
jqueryasp.netajaxfile-exists

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!


Solution

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