The Basics
We are going to create a jquery + html + css image loader. This means, the browser will load the first image, then the next and so on. Its actually quite simple and can make the viewing experience of an html gallery a lot less frustrating.
How does it work
Instead fo creating <img> tags, we will create <div> tags holding the image info like src and alt. Then we will use jQuery to turn the div into an img 1 by 1. Lets get started.
HTML Markup
<div class="loading"></div>
<ul>
<li><div id="1" src="my-image1.jpg" class="loadable-image" alt="text"></div></li>
<li><div id="2" src="my-image2.jpg" class="loadable-image" alt="text"></div></li>
<li><div id="3" src="my-image3.jpg" class="loadable-image" alt="text"></div></li>
</ul>
CSS Markup
.loading
{
width:16px;
height:16px;
padding:6px;
background:#000 url(images/ajax-loader.gif) 50% 50% no-repeat;
position:absolute;
z-index:99;
top:50%;
left:50%;
margin-left:-10px;
margin-top:-10px;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
}
ul
{
padding:0px;
margin:0px;
list-style:none;
}
ul li
{
float:left;
padding:0px 20px 20px 0px;
}
Javascript / jQuery
$(document).ready(function(){
// hide all image divs
$('.loadable-image').hide();
// load first image
loadNextImage();
});
var imageCounter = 1;
function loadNextImage()
{
var div = $('.loadable-polaroid#'+imageCounter);
if(div.length){$('.loading').show();}
var img = '<img src="'+div.attr('src')+'" alt="'+div.attr('alt')+'">';
var parent = div.parent();
parent.html(img);
parent.find('img').load(function(){
// you might be able to use $(this) instead
parent.find('img').show();
$('.loading').hide();
imageCounter++;
loadNextImage();
});
}
How to make it better
- You could create a loop ( javascript or php) on the images to dynamically assign them id’s
I hope you find this code useful. Its really simple and works extremely well. If there are any problems with the code I have posted please let me know and I will fix it ASAP.