Tuesday, February 21, 2012

Beginners' Trick : Preloading Images using CSS without Javascript


Hello and welcome dear Developers. Today's tip is a very easy tip and very useful and saves lots of time. What if you make a photo gallery that contains 3 images, and when you hover on every image, it changes to another one. This requires that you make images like that :
<image src="images/image1.jpg" onMouseOver="this.src='images/image1-hover.jpg'" onMouseOut="this.src='images/ image1.jpg'" />

This piece of code will make 2 replaceable images, one standard, and one when you hover the mouse on it.

this action is pretty good, but when you do that, and test it online you will notice that loading the Hover image takes time !! so, we need to PRELOAD all images when the site opens. a known tip for that is to make a preload javascript function that loads all images before the page load.
But here is a very easy tip that is easier, and better than using javascript, it is using CSS.

HOW ????!

1- At the bottom of your html file, create your div that contains LOADED IMAGES like the folowing :

<div id="preloaded-images">
   <img src="images/image1-hover.jpg" width="1" height="1" alt="Image 01" />
   <img src="images/image2-hover.jpg" width="1" height="1" alt="Image 02" />
   <img src="images/image3-hover.jpg" width="1" height="1" alt="Image 03" />
</div>


2- In your css file, write the following style ( or in the header, inside <style></style> ) :

div#preloaded-images {
   position: absolute;
   overflow: hidden;
   left: -9999px; 
   top: -9999px;
   height: 1px;
   width: 1px;
}

this way will load all your images, and the delay time will disappear. This tip works in all browsers well.

Enjoy your time developing nice galleries ;)

No comments:

Post a Comment