views:

123

answers:

2

On the home page of my site I want to display a lot of products which have images which are quite large. Currently the page is taking so long to load that it is actually timing out and the page fails to display!

In MVC, or just ASP.NET in general, how can I load an image asynchronously? Basically what I want to do is display the details of the product and just display a small loading image e.g. ajaxload.info. until the image is loaded.

I assume this is going to require some javascript/jQuery...

+2  A: 
<img src="ajax-loader.gif" onload="this.onload=null;this.src='bigimage.png';" />

or if you prefer unobtrusively:

<img src="ajax-loader.gif" id="myimg" />

and then:

$(function() {
    $('#myimg').load(function() {
        $(this).unbind('load');
        this.src = 'bigimage.png';
    });
});
Darin Dimitrov
@Darin: Thanks, can't believe how simple that was...Could you explain *why* though? I don't quite get how that works? Is it because javascript runs *after* the page content is loaded?
James
@James, the browser loads the HTML. Once it encounters the `<img>` tag it analyzes its `src` attribute and sends an additional parallel request to fetch it. As the ajax loader image is small it is fetched rather quickly. Once fetched it is shown on the screen and the `onload` event is raised. If the user has javascript disabled everything ends at this point. If on the other hand it is enabled it first detaches the `onload` event and modifies the `src` attribute to point to the big image. Once this attribute modified another async request is sent to fetch this image and once loaded it is shown.
Darin Dimitrov
@Darin: Thanks for clearing that up :)
James
+1  A: 

First off, it's worth checking that the sizes of your images aren't humongous and simply scaled to dimensions appropriate for the page. In order for the loading time to be as best as it can be, the images ought to be the exact size you want to display them, 72dpi and no more. The images will most likely be cached after they are fetched the firs time so it should just be a one time cost.

I would be inclined to return only the url to the image in your AJAX request. In fact, you wouldn't necessarily need to even make it an AJAX request. You could send out a JavaScript array of strings that have the urls to the images in it then create a new Image element (or similar) when the user hovers over a particular placeholder for the image.

Hopefully that's given you some ideas!

Russ Cam
@Russ: Thanks for the advice. The images are quite good quality so they can range from between 3kb up to 12kb. In terms of DPI they are all 96. It would be quite a job to actually manually resize these.
James