Front-end Web Developer | Tampa, FL

How to add images preload with CSS

Posted on: February 5th, 2010 by admin No Comments

First variant – using CSS property: DISPLAY: NONE

Fortunately, Cascading Style Sheets (CSS) offer you an easy and reliable option. Using the DISPLAY property, you can tell the browser to request an image, but NOT to display it on the page. The browser just requests the image from the server and caches it for future use.

First of all, we need to create class with display none, and add it to the Head of page:

{CODE type:php;}<style type=”text/css”>.preloadImg {display:none;}</style>{/CODE}

Or simple add this class in your_style.css

{CODE type:php;}.preloadImg {display:none;}{/CODE}

Next we have to add preload images to Your HTML home page. I recommend add this code to the bottom of your home page.

{CODE type:php;}<img class=”preloadImg” src=”my_preload_image.jpg” alt=”Don’t forget to add ALT” title=”Don’t forget to add Title” height=”100″ width=”100″ />{/CODE}

Note: don’t forget to add class preloadImg for the all preload images

 

Second variant – using CSS Sprites

 

In my previous articles a completely explain what is CSS sprites (Image sprites). I use this method for rollover menu. So in this article i’ll show just a method:

Create a new image that is as wide as your widest image and and as tall as the combined height of all your images plus X pixels, where X is the number of images you have. Now place you images into this new image, left aligned, one on top of the other with one pixel of white space in between.

Notice in the CSS that there is a single background-image applied to the anchor element itself, and the unique classes merely shift the background position with negative Y coordinates.

{CODE type:php;}
#nav li a { background-image: url(‘../img/image_nav.gif’) }

#nav li a.item1 { background-position: 0px 0px }
#nav li a:hover.item1 { background-position: 0px -72px }

#nav li a.item2 { background-position: 0px -143px }
#nav li a:hover.item2 { background-position: 0px -215px }
{/CODE}

So what we’ve got. The browser display only first image and the others will not display.

 

And the last one, if You are the fan JS code

 

If You want to add JS preload to your page add:

{CODE type:php;}<script_type=”text/javascript”_language=”JavaScript”>
var name_image=new Image(width, heght)
name_image.src=URL
</script>{/CODE}

For example we want to preload image with name ‘xxxx.jpg’ form ‘images’ folder:

{CODE type:php;}<script_type=”text/javascript”_language=”JavaScript”>
var xxxx.jpg=new Image(450px, 100px)
xxxx.jpg.src=”../images”
</script>{/CODE}

 

Ugh. I spent 2 hours to write this article and i hope it will help You :). And if you have any questions, leave me a comment.

Comments are closed.