Tuesday, May 29, 2007

Loading images asynchronously with JavaScripts

Sometime you may want to load a list of data in your web pages. Imagine that every row of your data has an image. So you can use a GridView control in your webpage and create you template. The point that I 'm goint to cover in this post is about how to load the images of your rows asynchronously!

It 's seems great to set a default image for your page that will be shown while the images is loading from the server asynchronously. Because that image is loaded once it will help your page load time. And then after page load completed you will start loading your images from server asynchronously.

Let 's start with creating the GridView control and setting an XML file for it 's datasource by using an XML Datasource object in our form. The source code would be something like this:

<asp:XmlDataSource ID="xmlDataSource1" runat="server" DataFile="~/App_Data/mySource.xml"></asp:XmlDataSource>

<asp:GridView ID="gridView1" runat="Server" AutoGenerateColumns="False" DataSourceID="xmlDataSource1" Enabled="false">
<asp:BoundField DataField="Author" HeaderText="Author" />
<asp:BoundField DataField="Title" HeaderText="Title" />
<img border="1" src="images/csharptuning.jpg" onError="this.src=csharptuning.jpg" onLoad="GetArticleImage(this,'<%# Eval("ImageUrl")%>');" width="125" height="125"/>

Notice that for loading the default image in each data row, I 've set the "src" attribute of my image control to a default value like src='csharptuning.jpg'.I have also set something to load the actual images asynchronously after the loading of image controls.

So, first I create a web page which is give me my images dynamically by a QueryString. (I have been explained how to create these kind of pages here).

Then I have to set it to load the actual image after the image control loaded. For this purpose I create a JavaScript function in my page like this:

function GetArticleImage(img, url)
img.onload = null;
img.src = 'GetImages.aspx?fname=' + url;


and then I added onLoad='GetArticleImage(this,<%# DataBinder.EvalContainer.DataItem,"ImageUrl") %>' event on my image control.

Now you can start your page, then you will see that in first seconds you will get a default image for each record, but after some seconds (in my code is 5") you will get the actual result of your images.

You can also download this sample by this link:


Rem said...

The blog is helpfull...
visit also asp.net example

Anonymous said...

Not helpful at all.