Here’s a Great CSS Trick

While I’m handing out tips, I think I’ll share a CSS trick that I picked up somewhere (but can’t remember where) not too long ago. This cool little method will pre-load the images for your site theme without the need for any JavaScript. It’s too simple not to use it!

First, add an id selector to your stylesheet similar to the following:

#preload {
    width: 0;
    height: 0;
    display: inline;
    background-image: url(images/background.gif);
    background-image: url(images/banner.gif);
    background-image: url(images/logo.gif);
    background-image: url();
}

The critical thing here is the size (width/height: 0), to display it inline (no box of it’s own) and that the last background image url be empty so nothing shows as a background (even though the width/height is 0).

Then in your page, right after the “<body>” tag, add an empty div element as such;

<div id="preload"></div>

That’s it. As soon as your page loads, the style images are downloaded and stored in the browser cache. No need for a JavaScript function to do it anymore. Slick, huh? Works great for those who prefer to browse with JS disabled too.

Yes, it adds just a little superfluous code to the page, but it’s far less cumbersome than the JS alternative, and far more manageable when you want to add or remove images.

There you have it. Enjoy!

iTunes, App Store, iBookstore, and Mac App Store
About Jim Mitchell

Jim started out with a Mac SE/30 and a whole lot of love for that machine. It was during those early years working with PageMaker, Freehand & Photoshop that he learned the importance of keeping a system in tip-top shape. Now, as a systems admin with more than 20 years of experience under his belt, Jim’s ongoing efforts help keep the Macs of others running smoothly. You can follow Jim on Twitter at @jimmitchell.

Comments

  1. Shahid says:

    Plz define what is the use of this code……… Thanks

  2. Jim Mitchell says:

    Re-read the article – because the second sentence clearly explains the purpose of the code: To preload images used in CSS, and cache them before an HTML page finishes loading.