I've used this usefully little plugin on several projects, and Scott Hansleman recently highlighted it in his Pinching pennies when scaling in The Cloud blog post. It's useful for situations where:

  • ou want to load images based on some convention but aren't sure if they exist
  • You want to load only images that the use is able to see on their page

 

ake this example that I've been working on this week. It's a leader board for our timesheeting application that shows the current top biller for the year

Figure: Bad Example - Broken images everywhere

n this instance, the employee profile images are being loaded by convention, and not all employees have photos, that's why you see broken images here. Now there's a few ways of solving this:

  1. heck the file system for the employee file (this has a few problems)
  2. heck via HTTP the image exists on the external server

The problem with checking the file system is, that the file can still be broken if it is trying to get an image served from a CDN instead, 

Checking via HTTP headers is possible and can be done without downloading the file but as always, if you have lots of files this can slow down the rending of your page.

jQuery.LazyLoad is a great client side solution as we first render a placeholder image and then (on the client side) request the actual image and then replace the placeholder with the downloaded image. It's very lightweight and simple to use.

    • Reference the jquery.lazyload.min.js file

     

     

     

    <script src="@Url.Content("~/Scripts/jquery.lazyload.min.js")"></script<
    
    • Render the image tags as follows:
     <img class="full lazy" data-original="@emp.PhotoUrl" src="@Url.Content("~/Content/EmpPhotos/placeholder.png")" />
    
    • Call the lazyload() method on document ready
       <script>
            $(function() {
                $("img.lazy").lazyload();
            });
        </script>
    

    Now all the broken images have a place holder image by default, and the client downloads and replaces the employee photos for employees who actually do have a photo.

    26-04-2013 9-04-48 AM.jpg

    Figure: Good Example - Image placeholders show up instead of broken images

    Comment