Fall Sale! Code FALL2024 takes 25% OFF our Pro Plugins & Books »
Web Dev + WordPress + Security

Pure CSS: Better Image Preloading without JavaScript

[ Preload Images with CSS ] After reading my previous article on preloading images without JavaScript1, 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="https://perishablepress.com/image-01.png" width="1" height="1" alt="Image 01" />
   <img src="https://perishablepress.com/image-02.png" width="1" height="1" alt="Image 02" />
   <img src="https://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 = Creative thinker. Passionate about free and open Web.
GA Pro: Add Google Analytics to WordPress like a pro.

29 responses to “Pure CSS: Better Image Preloading without JavaScript”

  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?

  2. Perishable 2008/04/16 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!

  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?

  4. Perishable 2008/04/16 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! ;)

  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.

  6. Perishable 2008/05/04 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! ;)

  7. Kevin Keinert 2008/05/28 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.

  8. Perishable 2008/05/28 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..

  9. Kevin Keinert 2008/05/28 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.

  10. Perishable 2008/05/31 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 ;)

  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

  12. SneakyWho_am_i 2008/09/26 2:43 pm

    Perfect!

Comments are closed for this post. Something to add? Let me know.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
Digging Into WordPress: Take your WordPress skills to the next level.
Thoughts
I disabled AI in Google search results. It was making me lazy.
Went out walking today and soaked up some sunshine. It felt good.
I have an original box/packaging for 2010 iMac if anyone wants it free let me know.
Always ask AI to cite its sources. Also: “The Web” is not a valid answer.
All free plugins updated and ready for WP 6.6 dropping next week. Pro plugin updates in the works also complete :)
99% of video thumbnail/previews are pure cringe. Goofy faces = Clickbait.
RIP ICQ
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.