Web Development for 2012

Alexander Dickson - Web Developer covering PHP, jQuery / Javascript, XHTML, CSS, more

A quick (albeit hacky) way to preload images using CSS

Published on Sunday, 11th April 2010.

Often, I have an element I display based on user interaction with JavaScript, and it always annoys me when there is a new image in the element which has not been cached. The ugly flash (and possible redrawing of the layout) is something I'd much rather avoid.

Sometimes this is unavoidable, and for good reason. I mean, if this image is over 30kb or so, I'd much rather load it on request then preload it. However it would generally be a good idea to display a throbber whilst downloading the new image. This can be achieved using the JavaScript load event on the image.

But when it comes to showing an error symbol that is only 715 bytes, it can be safely assumed an extra HTTP request is OK. Of course, you could completely forego this by using CSS sprites, but this post won't cover that here.

So my little trick, is to simply add the image as a background image to an element which does not currently have one. You must also set it to not repeat, and to be positioned out of view.

<style type="text/css"> #some-element { width: 300px; height: 250px; background-image: url(../images/preload-me.png); /* preload this image */ background-repeat: no-repeat; background-position: -9999px -9999px; } </style>
It would be better to use shorthand, but it doesn't fit as well in my page layout.

Note too, this has a number of caveats. You must make a note to other developers and to yourself exactly why you are adding the background image that won't be visible. It also becomes a problem if you intend to use a background image on that element later. There are trade offs with everything :)

Comments

  • Alexander Dickson

    Posted on Friday, 7th May 2010 @ 2:45pm.

    @Braden I considered that, but I wanted to keep extraneous elements to a minimum.

  • Braden Schaeffer

    Posted on Friday, 7th May 2010 @ 2:26pm.

    You could always do this:

    <span style="display: none;">
    <img />
    <img />
    <img />
    </span>

Leave a Comment

Comment Details

Your email will never be displayed. If you have a gravatar, it will be displayed.

Note: Your comment may require approval before it is posted to the site.

Stack Overflow Profile

view full profile »

About

I'm a web developer from the Sunshine Coast, Australia. more »