Best practice for deferred image loading


The speed a website loads and is ready to interact with is a very important element is web design and has nothing to do with graphics design.

One method to decrease the time for the browser to be ready for interaction is by having parts of the page load after the basic initial graphics design is presented.

Elements that have depth that can be deferred include slide shows and perhaps some interactions and animations. These elements can be loaded after a small delay.

$(document).ready(function() {
setTimeout(images, 750);
}

An onload event may also be used with images but it is buggy with IE. Specifically if the images have been cached. The work around has to do with the order of functions in the Javascript.

Bad:

var img = new Image();
img.src = "image.jpg";
img.onload = function() {
/* function */
}

Good:

var img = new Image();
img.onload = function() {
/* function */
}
img.src = "image.jpg";

This can be handled with jquery.

$(document).ready(function() {
var newImage = "images/002.jpg"; //Image name

$("a.tnClick").click(function() {
$("#myImage").hide() //Hide it
.one('load', function() { //Set something to run when it finishes loading
$(this).fadeIn(); //Fade it in when loaded
})
.attr('src', newImage) //Set the source so it begins fetching
.each(function() {
//Cache fix for browsers that don't trigger .load()
if(this.complete) $(this).trigger('load');
});
});
});

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: