Pure CSS: Better Image Preloading without JavaScript

Published Tuesday, April 15, 2008 @ 12:34 pm • 15 Responses

After reading my previous article on preloading images without JavaScript 1, Nanda pointed out that adding extra markup to preload images is not the best approach, especially where Web Standards are concerned. Mobile devices, for example, may experience problems when dealing with the following preloading technique:

/* ADD THIS TO CSS */
div#preloaded-images {
   position: absolute;
   overflow: hidden;
   left: -9999px; 
   top: -9999px;
   height: 1px;
   width: 1px;
}

<!-- ADD THIS TO XHTML -->
<div id="preloaded-images">
   <img src="http://perishablepress.com/image-01.png" width="1" height="1" alt="Image 01" />
   <img src="http://perishablepress.com/image-02.png" width="1" height="1" alt="Image 02" />
   <img src="http://perishablepress.com/image-03.png" width="1" height="1" alt="Image 03" />
</div>

Thus, as Nanda suggests, it is better to preload images using only CSS. Using the CSS background property, we can preload images via existing <div>s, <span>s, or other elements in the (X)HTML markup.

Let’s say you have three images (e.g., image_01.png, image_02.png, and image_03.png) that you would like to preload using this method. First, examine your markup for three identifiable <div>s (or other elements) that may be used as CSS hooks for the preloaded images. For example, looking at the source code of the current page, I would choose the following three divisions:

  • <div id="wrap">...
  • <div id="jump">...
  • <div id="header">...

Then, to implement the preload, I would add the following code to my site’s CSS file:

div#wrap {
	background: url(image_01.png) no-repeat -9999 -9999;
	}
div#jump {
	background: url(image_02.png) no-repeat -9999 -9999;
	}
div#header {
	background: url(image_03.png) no-repeat -9999 -9999;
	}

Here, we are preloading each image into its own unique <div> and then preventing its display by positioning it to the far left of the browser window. If the preloading elements are empty with no discernible height or width, hiding the preloaded images off-screen should not be necessary because they will not be displayed. Even so, it is probably a good idea to relocate them just to be safe.

Of course, once you have implemented this code to preload your images, they will be immediately available (depending on size) for display in your document as needed. Simply refer to them as normal using whatever CSS code that you would normally use. For example, once these images have preloaded, I could employ the following :hover technique with minimal presentational delay:

a#first:hover {
	background: url(image_01.png) no-repeat 50% 50%;
	}
a#second:hover {
	background: url(image_02.png) no-repeat 50% 50%;
	}
a#third:hover {
	background: url(image_03.png) no-repeat 50% 50%;
	}

According to my tests, this technique works well in any browser (including IE 6) that supports the CSS background property. Best of all, this preloading method is entirely unobtrusive, requiring no presentational code and degrading gracefully in non-supportive browsers.

Footnotes


Dialogue

15 Responses Jump to comment form

1teddY

April 16, 2008 at 7:00 am

Nice! I’ve never thought of preloading images as background images with a heavily displaced position. I usually use the problematic preloading technique, but I guess it’s better to preload images in background to ensure cross-browser and cross-device compatibility. Just a question though - if that container has a background image assigned to it, then should we create empty containers to preload the images?

2Perishable

April 16, 2008 at 7:57 am

Hi teddY :) No need to create empty elements (such as <div>s) for background images. Any available element on the page (that doesn’t already have a background image assigned to it) will work just fine. It doesn’t have to be the same element (or even one next to it) that contains the presented image in the document. So, given enough markup on a page, it should be possible to preload everything you need without resorting to the creation of non-semantic markup (which would defeat the purpose of this method). Nonetheless, there are situations where it may be necessary to create an empty container element(s) just for preloading. For more information on that technique, check out this article. Cheers!

3Trav

April 16, 2008 at 10:57 am

One could also make the various constituent image elements into a single large image, which could then be positioned using css. Maybe unwieldy for a large site, but could actually improve the load time of a small site; plus, then you only need one element in order to preload all the images - or is that too crazy?

4Perishable

April 16, 2008 at 2:56 pm

Absolutely, whenever feasible, I highly recommend using CSS sprites to optimize performance. While it often difficult to combine and display every image on an average-size site, it is frequently straightforward to combine similar images, such as used for lists, links, and logos. As you say, combining images decreases time required for page load and image display, while also reducing the number of overall server requests. Excellent point, Trav — thanks for the reminder! ;)

5Stephen Cronin

May 1, 2008 at 11:31 pm

Hi Jeff,

I’m not sure about this - using this method means that there’s no alt tag. Isn’t that bad for accessibility?

I mean if someone with a visual impairment uses a text to voice reader to listen to the page, then it reads the alt tag doesn’t it, so if we use this method, then there is nothing to be read for the images.

I appreciate the images are hidden for the moment, but when you display them, is there anyway of adding the alt tag?

I’m a little cloudy about all of this and I’m not speaking from authority, but that was my impression.

Very interesting nevertheless.

6Perishable

May 4, 2008 at 8:19 am

Hi Stephen :)

Good to see you again! You raise some good points; allow me to explain my reasoning. First, for implicit imagery, such as background images, list deco, and other design-related elements, alt descriptions are not required because they are unnecessary. For explicit images, such as photos, diagrams, and other primary content, you are correct, alt tags are very important, especially for usability and accessibility issues. Fortunately, the method described in the article enables you to call and display the preloaded images implicitly via CSS or explicitly via (X)HTML anchors. This of course gives you control over which images include alt descriptions and which do not. So long as the exact same file path is used for both the preloaded and displayed images, either display method will work just fine. I hope that helps — I am by no means an expert in this area either, but I do work with this stuff all day and love sharing as much as possible with my readers. Thanks again for dropping by! ;)

7Kevin Keinert

May 28, 2008 at 7:46 am

Hello, I have a question on preloading images. I am preloading four images on my website, which can be seen at http://www.keinert.com -I am using these to change the image of my links when the mouse moves over them.

However, something is still wrong because when I move my mouse off of the “spinning red ball links,” my browser still has to download the spinning blue ball each time.

What am I doing wrong?
Thanks, Kevin.

8Perishable

May 28, 2008 at 9:35 am

Hi Kevin, a couple of questions: First, how did you determine that the browser must re-download the image(s) after removing the cursor? Checking the site in Firefox shows no such activity. Second, this may be a caching issue. I am showing that your images do not possess far-future expires headers. That may be something to look into..

9Kevin Keinert

May 28, 2008 at 4:32 pm

Hello, thanks for the reply! I’m assuming that the blue_ball image reloads every time the mouse moves off a link, because at the very bottom of my IE6 browser, I see the message “downloading…blah,blah,blah…/bb_ball.jpg”

Sometimes the download is slow and the image takes 2 or 3 seconds to change. Most of the time it’s instantaneous.

If this is a caching issue, can you provide more info on how to troubleshoot? I don’t know what far-future headers are.

Thanks, Kevin.

10Perishable

May 31, 2008 at 2:51 pm

Have you tried using CSS instead of JavaScript? Place this in your CSS file:

/* show the blue ball by default */
.ball a {
background: url(path/bb_ball.gif) no-repeat center left;
padding-left: 33px;
}
/* show the red ball upon hover */
.ball a:hover {
background: url(path/ry_ball.gif) no-repeat center left;
}

And replace your markup with something like this:

<h3><a class="ball" href="http://domain.tld/path/etc/" title="Description of the link">Title of the link</a></h3>

No JavaScript required!

Remember to edit the image paths in the CSS code to match your own. You will probably want to tweak the markup as well, according to your needs.

Once that code is in place, you may find that preloading is not necessary. If it is, then perhaps the preloading method described in this article will provide some relief ;)

11Lukas

August 17, 2008 at 2:32 pm

Hello there Im currently trying to devolop my homepage for displaying animaiton videos and art images and I came across this webpage when trying to solve this problem of mine. Im trying to create a gallery where you can see the thumbnails of the pictures and when you click on a thumbnail the image will enlarge in a maximum resolution of 800×800 pixels. Beside the image I have 2 arrows pointing in left anr right, when you click on these images it should display the next image in the gallery or previous depending on which one you click. The gallery will not be visible because the image itself will cover it when enlarged. Now what I want to do is to preload and reload all of the images on in the gallery. Cause if I click on the next arrow I dont want to load a hole nother page just to come to the next image if you understand what I mean. So what I want to be able to do is to reload a portion of the webage and not the hole because all of my external links like, About me, photo showreel and so on , and the background should not be reloaded all the time, even thou it is saved in the cache I feel that it is not the best way to do this. So the most optimal way would be if all the images are loaded when you enter the site and when you clikc on a thumbnail that image is displayed and when you click on the next or previous arrow the next images or previosu image is displayed without having to refresh the or reload the page.

Is this possible to accomplish without javascript ? or is there a nother way to do it? I find that it is possible to accomplish with a:hover if you have your thumbnail gallery beside or something else to hover over to display your images. But nothing that can actually fix my problem. thank you for your time

12SneakyWho_am_i

September 26, 2008 at 2:43 pm

Perfect!

13Surat Web Hosting

October 5, 2008 at 6:06 am

Thanks for this,

we did face lot of problems on few sites, where images are used everywhere. I hope using this technique helps me solves the problem.

Thanks for it.

Regrds
Synergy Informatics
Surat Leading Web Hosting & Design Company

14Jeff Starr

October 5, 2008 at 10:48 am

Likewise, SWH, I hope the code works well for you. I tend to post quite a bit about CSS/JavaScript image preloading, and also about image optimization in general. In fact, I have a new article on image preloading that will post soon. Grab my feed for all the action! ;)
Cheers,
Jeff

15Synergy Informatics

October 5, 2008 at 10:15 pm

Hi Jeff,

I would like to read more from you… especially compared to other blog, cause your articles are simple & effective and answers the problems in perfect sense.

Thanks
Krunal
Synergy Informatics

Subscribe to comments on this post


Share your thoughts..

TopRead official comment policy

Contact Perishable Press

  • Contact Jeff via form

Search Perishable Press

About Perishable Press

Perishable Press is the virtual playground of Jeff Starr — visionary, founder and lead developer of Monzilla Media, a small web and graphic design company in the lush desert oasis of Moses Lake, Washington. Perishable Press features articles and tutorials on many aspects of digital design..

Read more..

Perishable on Twitter

automation is great: i've got photoshop batch processing 300+ images while FTP is simultaneously uploading them to the server..

Perishable on Tumblr

Tons of Firewalls

Tuesday, 7 October 2008, 1:45 am

Recently overheard on conservative talk radio (instructing listeners how to obtain a free promotional video from their new website):

“This website has tons and tons of firewalls, so you have to use your real email address to download the video..”

The Quiet Search Revolution

Monday, 6 October 2008, 12:15 pm

Just a thought.. As awesome as Google is these days, it would suck if they ended up owning the entire search-engine business. When they get to the point where all competition is impossible (due to their sheer size, financial resources, media influence, etc.), how many alternate search engines will have the resources for continuous improvement and top-quality search results? When this happens, we will have no choice but to do exactly what Google tells us to do.

As deeply ingrained as it is for everyone to instinctively and unthinkingly turn to Google for their search activity, it is time to leave a few alternate search tabs open for as much use as possible. Instead of using Google just because that’s what you always do, try your search on MSN, Yahoo, Ask, or any of the other independent search engines instead. Sharing traffic with other search engines is a nice, quiet way to keep the competitive spirit alive and well in the search-engine business.

Disappearing WordPress Posts

Wednesday, 1 October 2008, 7:50 pm

Today I experienced difficulties while trying to publish or even save new posts in WordPress. I would compose the post as usual, add all of the keywords, tags, meta tags, and so on, but as soon as I clicked the “Publish” or “Save” button, the post would just disappear from existence.

The weird thing is that during the drafting process, WordPress’ default auto-save feature showed that the post had been saved at expected intervals. Unfortunately, after trying to publish several different posts, WordPress showed absolutely no record of the posts ever being created. They simply vanished into thin air.

Fortunately, a little investigation revealed the culprit. If you should find yourself dealing with this same issue, here are some different things that you should try. First, re-upload fresh copies of your entire WordPress installation. I don’t know why exactly, but apparently various files can either go stale or completely disappear from the server. Overwriting or writing fresh files may do the trick.

If that doesn’t work, check your WordPress database for errors. In my case, a little investigation revealed that something had caused a couple of fatal errors in the wp_posts table. Fortunately, checking and repairing the table solved the issue.

Tumblr Battles

Wednesday, 1 October 2008, 5:30 pm

Please excuse the duplicate Tumbr posts.. seems there is no way to ping Tumblr to refresh/rebuild the RSS feed according to changes in post content. So, to resolve the issue I have discussed now like two or three times regarding paragraph elements and proper feed formatting, I have no choice but to repost a majority of my text posts.

This is necessary for the proper import and display of my Tumblr feed into WordPress. Currently, there are five items displayed at once, each styled according to proper inclusion of paragraph tags. Thus, whenever the Tumblr feed “forgets” to enclose single-paragraph posts with the proper tags, the result is an unstyled post entry displayed on my site.

Assuming that makes sense, you will please excuse my dust while I repost a few older entries in an attempt to reconstruct (the hard way) a properly formatted Tumblr feed.

More Optimization Measures

Wednesday, 1 October 2008, 5:27 pm

Another important step in improving the performance of my recent redesign involves the optimization of both CSS and JavaScript content. During development there were around 15 server requests for these two types of files, 10 JavaScript files and 5 CSS files. This was okay for my own use, but would not work for production purposes.

Optimizing these file types involves consolidation, compression, and caching. Consolidation of 10 JavaScript files into three is huge improvement. Now I deliver one JS file for the functionality of the site, one for Mint, and another for Analytics. Likewise for the stylesheets; after consolidation, a single stylesheet is delivered to all modern browsers. There are two additional stylesheets as well, but they are targeted at IE6 and mobile browsers and will not load elsewhere.

Once the files were consolidated as much as possible, it was time to optimize or “crunch” them. Using the sexy Flumpcakes CSS optimizer, I was able to reduce my stylesheets by around 25%. Likewise for JavaScript, I used xtreeme.com’s optimizer to shave an additional 20% off the size of my JS content.

Finally, once I had consolidated and compressed my JS and CSS files as much as possible, I wanted to further my optimization efforts by ensuring that these files were cached by the browser. By setting far-future Expires headers for everything but the statistical files, my site gains an additional performance boost by eliminating the need to reload preexisting content.

Read more on Tumblr..

Subscribe to Comments Recent Dialogue

  • Adam Singer: Thanks for this. You're right, if it isn't broken, don't fix it. I was about to update my permalinks and install a plugin to redire...
  • Marilyn: It looks great on my browser! I wish I had that much creativity in my head! It's gorgeous!...
  • Randy: "Too girly?" It looks like a great design. Define "too girly!"...
  • Christopher Ross: .htaccess based redirects are wonderful. I'm always baffled by web professionals who don't take the time to learn more about them....
  • federico: Hi Jeff... tnx so much...it worked perfectly... c u Federico...
  • Cooltad: The skin seems (mostly) fine in my expert opinion. Your one of the few people able to make a design with a transparent table and a b...
  • Neal: The free Intro to Linux book is a great place to start http://www.ischool.utexas.edu/mirrors/LDP/LDP/intro-linux/html/index.html ...
  • Louis: @Jeff: Your “Archives” page is slick, although I would expect a cleaner implementation from such a vehement advoc...
  • Jeremy: Well I think that you may be over-critical, I don't see a darn thing wrong with it - I like it a lot!...
  • Jeff Starr: Alright, this is exactly the kind of information I was hoping to get. Lots of great ideas and recommendations here. I will be reading...

Read more recent comments..