Home » Internet » Web Designing » How to preload images with CSS

How to preload images with CSS

You should preload images with CSS so that the process doesn’t have to depend on JavaScript. Read how to preload images with JavaScript. There are many benefits of using CSS for preloading images and one of them is that even if the user has JavaScript turned off, you can still preload your images to render a decent user interface.

You can preload a single image with CSS and you can also preload multiple images. But doesn’t preloading your images make your website load very slow? Yes, it does, and that’s why you should preload images that are absolutely necessary. For example, preload just those images that you require for mouseover or rollover effects.

Preloading a single image with CSS

It’s better to have all your CSS definitions in a separate file, so let’s assume you have a file called mystyles.css where you store all your CSS style definitions. In this file, you can define a class

        display: none;

So simple, isn’t it? Now, somewhere in your source code, before the image is actually displayed or used, put the following code:

<img src=”image.png” class=”dontshow” />

By the time you use this image, it is already loaded.

Preloading multiple images with CSS

You normally have a rollover effect in your navigation and a navigation system may need multiple images. This is how you preload multiple images with CC:

<div class=”dontshow”>
        <img src=”image1.png” />
        <img src=”image2.png” />
        <img src=”image3.png” />

Since the display property of the entire DIV is set to none, whatever occurs within that DIV is hidden. So all your images are preloaded, but they hidden from your users and visitors.