Pure CSS: Better Image Preloading without JavaScript

by Jeff Starr on Tuesday, April 15, 2008 26 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 -9999px -9999px;
	}
div#jump {
	background: url(image_02.png) no-repeat -9999px -9999px;
	}
div#header {
	background: url(image_03.png) no-repeat -9999px -9999px;
	}

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

About the author

[ Jeff Starr ]

Jeff Starr is a web developer, graphic designer and content producer with over 10 years of experience and a passion for quality and detail. Jeff is co-author of the book Digging into WordPress and strives to help people be the best they can be on the Web. + Follow Jeff on Twitter and subscribe to Perishable Press for quality web-design content delivered fresh.


26 Responses

Add a comment

[ Gravatar Icon ]

teddY#1

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?

[ Gravatar Icon ]

Perishable#2

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!

[ Gravatar Icon ]

Trav#3

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?

[ Gravatar Icon ]

Perishable#4

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! ;)

[ Gravatar Icon ]

Stephen Cronin#5

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.

[ Gravatar Icon ]

Perishable#6

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! ;)

[ Gravatar Icon ]

Kevin Keinert#7

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.

[ Gravatar Icon ]

Perishable#8

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..

[ Gravatar Icon ]

Kevin Keinert#9

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.

[ Gravatar Icon ]

Perishable#10

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 ;)

[ Gravatar Icon ]

Lukas#11

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

[ Gravatar Icon ]

SneakyWho_am_i#12

Perfect!

[ Gravatar Icon ]

Surat Web Hosting#13

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

[ Gravatar Icon ]

Jeff Starr#14

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

[ Gravatar Icon ]

Synergy Informatics#15

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

[ Gravatar Icon ]

Rom#16

I have a similar problem to Lukas (#11 above). I want to display a Flash streaming gallery that uses a list of images (maintained in an xml files). So, the images are streamed/loaded sequentially and this is an improvement over embedding all of the images in the video. But, there is a delay in the display of the large images the first time through the gallery show (while the thumbnails below the large image display instantly).

The problem is that this may be a large number of images, and embedding the background image statement in dozens of CSS elements is not practical. So, what is the next best technique? Would it be to create a long list at the bottom of the calling page so that the images are loaded before opening the gallery page, along the lines of the example above:

Thanks for any additional advice.

[ Gravatar Icon ]

Jeff Starr#17

@Rom: Ugh! WordPress gobbled your code! Please repost using <code> tags wrapping each line of code, or, simply email me (Jeff at this domain) directly with the code and I will update (and respond to) your comment.. Thanks!

[ Gravatar Icon ]

Sp.Shut#18

I say why attaching the background images to some obscure divs, spans etc, when we could declare the neccessary background images on the neccessary elements but just with a big background-position value like -9999px and only change the position on hover or whenever needed.

Does it make sense?

[ Gravatar Icon ]

Jeff Starr#19

@Sp.Shut: Yes, makes complete sense — thanks for sharing that great tip with us! :)

[ Gravatar Icon ]

Serge Krul#20

just wanted to note that the values must end with a unit like “-9999px”.

when i tried copy-pasting “-9999″ it didn’t work (FF3).

ah, and thanx for this excellent post! :)

[ Gravatar Icon ]

Jeff Starr#21

@Serge Krul: Ack! Yes, you are correct - my bad. Units are definitely required for the positioning to work properly. Thanks for the catch. I have updated the article with the correct information. Cheers.

[ Gravatar Icon ]

Bathrobewarrior#22

I’ve heard of doing it this way though I find that a lot of times, it doesn’t seem to noticeably preload. I usually just end up using the 1 image sliding technique for buttons etc. Other images, I just try to make them small enough to not even matter. :)

I will definitely try this out though!

Cheers!

[ Gravatar Icon ]

marion#23

hey Jeff,

A few days ago I manage to solve my problem in regards to rotating my homepage photos using your site =D

thanks again for that again..hope you don’t mind me asking a little bit more in regards to this preloading topic of yours…

You see, I have about 100+ photos in there with 290X230 dimensions (320×260 when hovered)….I’ve been trying to integrate jquery lazyload plugin into my wordpress for the past two days but it seems like its not working…after reading your image preloading topics, I went to double check my theme’s style.css and its corresponding theme.js file to see if my theme is already using the preloading technique….this is what i found:

=================
in style.css:

div.photo {
/* background:url(img/sampler.jpg) center center no-repeat;*/
       width:230px;
       height:290px;
       float:left;
       overflow:hidden;
       position:relative;
       margin:0 1px 1px 0;
       /**/
       opacity:0;
       filter: alpha(opacity=0);
       -moz-opacity:0;
       khtml-opacity: 0;
}

.blankphoto {
       width:230px;
       height:290px;
       float:left;
       overflow:hidden;
       position:relative;
       margin:0 1px 1px 0;
       background-color:#000000;
}

#highlight {
       width:260px;
       height:320px;
       float: left;
       background-color:#666666;
       display:none;
       border:3px solid #ffffff;
}

///////////theme.js//////////////////////

$(function() {
       var left;
       var top;
       var bgimage;
       $("div.photo").hover(
              function () {
       var offset = $(this).offset();
       left = offset.left-18;
       if (jQuery.browser.msie) {
                            top = offset.top-17;
       } else {
                            top = offset.top-18;
       }
       bgimage = $(this).css('background-image');
       $('#hack').css({'display' : 'block', 'position' : 'absolute', 'background-image' : bgimage, top : top+'px', left : left+'px'});
       $('#highlight a#highlightlink').attr({
                            href: $(this).children('a').attr('href'),
                            title: $(this).children('a').attr('title'),
                            alt: $(this).children('a').attr('alt')
                     });

              },
              function () {
                     //out
              }
       );

       $("#highlight").hover(
              function () {
                     //over
              },
              function () {
                     $(this).css({'display' : 'none'});
              }
       );

       /*****/
       $("div.photo").each(function (i) {
              $(this).animate({
                     opacity: 0
              }, 0 )
       });
===========================

Jeff, please can you confirm PLEASE if my theme is preloading the images as background? if so, will jquery lazyload plugin work if the images are already loading as a background??? i tested my website homepage loading time with 42 images and the result is 16 queries in 0.29 seconds, i don’t know if that suppose to be good…i’ve already integrated wp plugin css sprites but want to speed it up some more to accomodate my 100+ images..

Thanks…sorry for the looong comment..

[ Gravatar Icon ]

Darren#24

I’ve been researching this for a while and I think this technique is the most reliable while also not messing with accessibility or creating extra markup. I’d also add that for accessibility it’s usually recommended to put your navigation into an unordered list so the ‘li’ parent elements of the anchors that require hover images are good candidates for the preloading images using this technique (assuming your hover images are for navigation elements and your parent list items don’t require background images themselves).

Trackbacks / Pingbacks
  1. mashempires.com » Blog Archive » CSS: Pre-load images with background-property
  2. The Best Way to Preload Images - techblog
Share your thoughts..

Read Comment Policy

Comment Rules: No spam. No profanity. Use your real name. You may use simple HTML tags for style. Wrap all code in <code> tags. Learn more.



Attention: Do NOT follow this link!