Adding a preloader to Images

Most websites have issues with load times, especially ones dealing with large quantities of media. Easiest solution for this? ... add a preloader.

jquery has an easy solution to preloading content. Using the .load() function, you can make sure that images get preloaded before displaying them on the page.

Below is a coding examples that works great in getting your content to display, when it is ready.

.imgHolder span{

background: url(images/preloader.gif);

width: 100px;

height: 100px;

overflow: hidden;

}

.imgHolder img{

display: none;

width: 100%;

}

$('imgHolder img').each(function(){

$(this).load(function(response, status, xhr){

if(status != 'error'){

$(this).css('display', 'block');

} else {

$(this).html('unable to load image');

}

})

})

You can add animations to the jquery display block and opacity if you want a more fluid transition, but this will work with most browsers, and display content once it's available.

There is also a pure javascript solution that is posted below. Remember you will need to traverse the entire document for images in an elementId to create a preloader for each item.

function preloader()

{

// counter

var i = 0;

// create object

imageObj = new Image();

// set image list

var imgHolder = document.getElementById('imageHolder').getElementsByTagName('img');

images = new Array();

for(var i = 0; i < imgHolder.length;i++){

images[i]=imgHolder[i].src;

}

// start preloading

for(i=0; i<=3; i++)

{

imageObj.src=images[i];

}

}

Be Sociable, Share!

One thought on “Adding a preloader to Images

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>