Thursday 8 January 2015

Asp.net Mvc Image Helpers (Part 3)

Image helper with lazy loading

This article looks at creating a html helper to lazy load images using the jQuery lazy load plugin.
It follows on from 2 earlier articles on creating html helpers for image loading:


There are a few different ways of making an image lazy load, but this seems to be the simplest to get working I've found so far.

First of all you need to install the Lazy load plugin for jQuery (search "lazyload") using the Nuget package manager. There are 2 versions available, I used 1.8.4. You will also need some additional images for this part, a ajax style loading spinner (create your own here!) and a 1x1 pixel spacer image (create one or download from here).

First we will create the html helper that will generate the html code that lazy loads the image.

 public static MvcHtmlString LazyLoadImage(  
               this HtmlHelper helper,  
               string image,  
               string alternative,  
               int width,  
               int height)  
 {  
   var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);  
   var url = urlHelper.Action("ImageResize", "Image", new { image, width, height });  
   var spaceUrl = urlHelper.Action("Image", "Image", new { image = "spacer.gif" });  
   
   var html = String.Format("<div class='lazyWrapper' style='height:{0}px; width:{1}px'>", height, width);  
   html += String.Format("<img class='lazy' src='{0}' data-original='{1}' alt='{2}'/>", spaceUrl, url,  
               alternative);  
   html += String.Format("</div>");  
   
   return MvcHtmlString.Create(html);  
 }  
It uses the Image Controller re-size method created in part 2 of this series.

We create a div element to wrap the img element, this enables us to set the background of the div to the loading spinner element and easily center the spinner. We set the img tags src attribute to a single pixel transparent image so that it will not show until updated by jQuery lazy load. The data-original tag holds the image that we want to lazy load.

Done!

No comments:

Post a Comment