HowToPlaza.com

How to wisdom from across the Internet — want to know how to do something? You may find the solution here.


How to preload images without JavaScript using CSS

Preloading images often helps if you want to create some effects that involves quick replacement of images, for instance mouseover. The image should change immediately in case of a mouseover because sometimes the user may move around the mouse pointer rapidly. If the mouseover image takes a long time to load it will create an empty box at the place of the mouseover effect and this will look bad for your design. You can easily preload images using JavaScript. You just need to use something like this code in JavaScript:

<script type="text/javascript">
var image1=new Image();
image1.src="/imagepath/thisimage.gif";
var image2=new Image();
image2.src="/imagepath/thatimage.gif";
</script>

This way you can preload as many images as you want. But the problem is sometimes your user may have JavaScript turned off in his or her browser. This doesn’t normally happen but it might happen so why take a chance? You can preload images using some CSS definitions in this way you don’t have to use JavaScript. Here is how you can achieve the same effect with some CSS and markup:

<style>
div#loadimages{
    display:none;
}

Then, somewhere on your webpage you can include the following markup:

<div id="loadimages">
<img src="/imagepath/image1.gif" width="1" height="1" />
<img src="/imagepath/image2.gif" width="1" height="1" />
</div>

You can load here as many images as you feel like and they will not show up because the display has been set to none. Now you can use the images using the same path wherever you feel like and they will show up immediately. Your webpage may take longer to load as a whole but you can keep the size of your images to minimum to make sure that not much delay takes place. This way you can preload images using CSS.

AddThis Social Bookmark Button

Posted by Amrit | Tags: Web Development


You can leave a response, or trackback from your own site.

Leave a Reply