Jul
5
2009

Faster Image Loading With jQuery



Comments available as RSS 2.0

Normally, if there are images on a webpage they’re there to support the content and not excessive, so you don’t have to worry about loading times. What if you need to have an undefined number though, and they happen to be high resolution like a gallery?

For the last site I worked on, the client wanted a gallery of 400×400 pixel images to cycle in a gallery on the front page of the site. They’re about 70KB each so if you’re loading 10 or more of them in the middle of the page, they’ll slow the page load down until they’ve all totally loaded.

The solution I used was to add the images to the DOM after the rest of the content loads.

The site was written in ASP.NET, but I used jQuery so it applies to any project.

First, you need to render a list of the images to load into a variable which JavaScript can access. Ie:

...
cmd.CommandText = "SELECT Filename, Description FROM tblGallery WHERE Visible = '1'";
StringBuilder jqueryBuffer = new StringBuilder("$().ready(function() {\n"); 
jqueryBuffer.Append("var galleryImages = [\n");
List<string> galleryPics = new List<string>();
SqlDataReader reader = cmd.ExecuteReader();
JavaScriptSerializer js = new JavaScriptSerializer();
while(reader.Read()) {
    galleryPics.Add(js.Serialize(new { 
        filename = Server.HtmlDecode(reader[0].ToString()), 
        alt = Server.HtmlDecode(reader[1].ToString()) 
    }));
}
reader.Close();
jqueryBuffer.Append(Utils.Implode(galleryPics, ",\n", false)).Append("];\n cycleGalleryPics(galleryImages);\n");
ScriptManager.RegisterStartupScript(this, typeof(Page), "jqueryListeners", jqueryBuffer.ToString(), true);
...

Which results in the following JavaScript on the page:

$().ready(function() {
  var galleryImages = [
  {"filename":"1","alt":"Picture 1"},
  {"filename":"2","alt":"Caption 2"},
  {"filename":"3","alt":"Something 3"},
  {"filename":"4","alt":"etc"},
  {"filename":"5","alt":""},
  {"filename":"6","alt":""}];
  cycleGalleryPics(galleryImages);
});

The cycleGalleryPics method just iterates over the array and creates an image for each element, then adds it to a named container on the document.

function cycleGalleryPics(galleryImages) {
    var galleryDiv = $('#Gallery');
    galleryDiv.html('');
    var path = "";
    if (typeof (imagePath) == 'undefined') {
        path = 'UserImages/Gallery/';
    } else {
        path = imagePath + '/Gallery/';
    }
    jQuery.each(galleryImages, function() {
        $('<img/>').attr({
            width: 368, height: 370,
            alt: unescape(this.alt),
            src: path + unescape(this.filename) + '.jpg'
        }).appendTo('#Gallery');
    });
    galleryDiv.cycle({ fx: 'fade', timeout: 3000, random: 1, fit: 1, containerResize: 0 });
}

The reason the contents of the container are cleared before adding the images is to provide support for users with JavaScript disabled. One image is added by an ASP.NET Image control so there won’t be a block of empty space.

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay

Comments

Leave a Comment

Login using OpenID or enter your details below to leave a comment.

OpenID
Anonymous


Comment

Powered by WP Hashcash