Introduction
So you want to preload images? There are two ways of doing this. The first is with Javascript, and you may be concerned that the user has Javascript turned off in his/her browser. The second alternative however, uses only CSS and (X)HTML, and I am going to show you the CSS (X)HTML way.
Where it can be used
Let's say you have a site that sells diamond necklaces, and you have now seen (from your control panel or any other source) that most users enter through your index/home page, and then they continue to the "products" page, and then they leave, this may be because they arrive on the products page and they have to wait for images to load and it takes too long, so what we'll do is, preload the images on the index/home page already, and when they arrive on the "products" page, the images are already loaded in the cache, or partially at least.
The CSS:
The CSS for this solution is very simple indeed, so simple, it only takes one line of code, and that line of code looks as follows:
img.hiddenpic{display:none}
Yes, that is all you need to add in your CSS file to preload images. So when you add an image with this class to your HTML the images will be loaded into the cache for future use, but they will not be displayed on the page because of the "display:none" that will hide the images from the user.
The (X)HTML
So here we are going to have a look at the code of our index/home page. We are already going to preload the images on this page, so that when the user browses to the "products" page, the images are already preloaded into the cache. This part should be placed right at the bottom of your page, just before the </body> tag, this way, all the other images on the page will load first and then the ones that need to be preloaded for the next page.
...
<img src='diamonds-1.jpg' alt='beautiful silver diamond necklace' class='hiddenpic' />
<img src='diamonds-2.jpg' alt='something special' class='hiddenpic' />
<img src='diamonds-3.jpg' alt='diamonds are a girl's best friend' class='hiddenpic' />
<img src='diamonds-4.jpg' alt='coming soon' class='hiddenpic' />
</body>
Conclusion
CSS gives a much better alternative for preloading images because it will always be rendered by the browser, where as Javascript could be turned off, and this code is much easier to implement than Javascript.
This page was published on It was last revised on