Home » Scriptalicious Blog » Webmaster » Using CSS to Preload Images Without JavaScript

Scriptalicious Blog

Using CSS to Preload Images Without JavaScript

Posted 2011-08-14 in Webmaster

Scriptalicious Blog

Preloading images on your website can help eliminate flicker and laggy hover effects on your images.

For a long time Web designers have used JavaScript to preload images. This has the benefit of loading images into the browser cache in the background, but it also relies on JavaScript support in the browser and several lines of extra JS code. (Or worse, the onload() property in some awkward implementations!)

The JavaScript Image Preloading Code

The code for JS image preloading typically looks like this:

image1 = new Image(); 
image1.src = "imagefile1.jpg";
image2 = new Image(); 
image2.src = "imagefile2.jpg";

This code uses JavaScript to preload the images, but requires a few lines of code for each image as you can see.

So, how do we do away with JavaScript for our preloader code? CSS to the rescue!

The CSS Image Preloading Code

The CSS method lets us implement a preloader without any JavaScript code at all.

The first step is to create a class that uses the display: none; property to create a hidden element which will contain our preloading images. The following CSS can go in your external stylesheet or be added inline.

.imagepreload { display: none; }

Now we can add the HTML needed for each image to preload. Insert the code anywhere in your BODY tags.

<div class="imagepreload">
<img src="imagefile1.jpg" width="1px" height="1px" alt="Preload Image 1" />
<img src="imagefile2.jpg" width="1px" height="1px" alt="Preload Image 2" />
</div>

Now the browser will load these images when the page loads, but our CSS properties will keep our explicit image tags from being displayed!

This is just one way of preloading images on your website, but it does present some advantages over the JavaScript counterpart.

There are also ways of using CSS to preload images using background images.

Any suggestions or tricks of your own are welcome.





 


Search



Subscribe


Subscribe via RSS

Stay current with Scriptalicious news and subscribe in your favorite RSS reader.

Subscribe by RSS

Subscribe via Email

Get the latest Scriptalicious news delivered to your inbox.




77 powerful SEO scripts for under $100.

Real-time Backlink Rank Checker script.


Scriptalicious is in no way affiliated with myspace.com® or Google®. Google, PageRank™ and MySpace are the trademarks of their owners.