A Way to Preload Images without JavaScript that is SO Much Better
Responding to my first attempt at preloading images without JavaScript, CSS-Guru David Bowman graces his audience with a most enlightening set of comments.
Apparently, the image-preloading technique explained in the article is “major overkill” and “totally ridiculous.” Of course, I will be the first to admit that I am no expert in CSS, but I do enjoy sharing my discoveries and watching as people improve upon them. My first attempt at preloading images without JavaScript may indeed be “pretty crappy,” but it certainly works.
Fortunately, several weeks prior to Mr. Bowman’s dazzling performance, insightful reader Duarte helps the community by sharing a far more elegant solution using display:
none;
. Here is an example of its implementation:
Step 1 — Place this in your CSS file:
div#preload { display: none; }
Step 2 — Place this at the bottom of your (X)HTML document:
<div id="preload">
<img src="http://domain.tld/image-01.png" width="1" height="1" alt="Image 01" />
<img src="http://domain.tld/image-02.png" width="1" height="1" alt="Image 02" />
<img src="http://domain.tld/image-03.png" width="1" height="1" alt="Image 03" />
</div>
Once in place, this code will ensure that your images are preloaded and available for use elsewhere in the document. Just remember to call the displayed images using the same path as the the preloaded images. After that, everything should work perfectly. Indeed, even CSS-Wizard David Bowman “tested it out” and agrees that “the problem is solved.” Thanks for the confirmation, David! ;)
Alternatively, to avoid the extra (X)HTML markup, you may simply add background images to existing elements that are either dimensionless or empty. For example, to preload three images, image_01.png
, image_02.png
, and image_03.png
, locate three appropriate elements in your markup and place something like this into your CSS file:
#element_01 {
background: url(path/image_01.png) no-repeat;
display: none;
}
#element_02 {
background: url(path/image_02.png) no-repeat;
display: none;
}
#element_03 {
background: url(path/image_03.png) no-repeat;
display: none;
}
..and that should do it! For more information on this technique, check out this article: Pure CSS: Better Image Preloading without JavaScript. And who knows, if we’re lucky, maybe Mr. Bowman will once again grace us with his presence! ;)
25 responses to “A Way to Preload Images without JavaScript that is SO Much Better”
Awesome, Dave — great to hear it! Thanks for the positive feedback :)