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

Preloading Images with CSS and JavaScript

[ Preloaded Image via CSS + JavaScript ] Fast-loading pages reduce errors, conserve bandwidth, and please visitors. One way to decrease loading times and enhance performance involves maximizing image display efficiency. Your mantra for achieving image efficiency should be “reuse, optimize, and preload.”. While each of these methods plays an important role, this article will focus on methods for preloading images. Consult your server error logs to identify web pages that may require image help. Note: preloading images does not reduce bandwidth! It only decreases apparent load time, thereby enhancing user experience.

Preloading via the CSS Display Property

This method is a very common method for preloading images via the CSS display: none; directive. To use this method, first add the following code to your CSS rules:

<style type="text/css">
<!--/*--><![CDATA[/*><!--*/
	img.preload { display: none; }
/*]]>*/-->
</style>

Then, add the preload class to each image tag that should be preloaded:

<img src="image1.jpg" alt="Image Caption 1" height="33" width="33" class="preload" />
<img src="image2.jpg" alt="Image Caption 2" height="33" width="33" class="preload" />
<img src="image3.jpg" alt="Image Caption 3" height="33" width="33" class="preload" />
<img src="image4.jpg" alt="Image Caption 4" height="33" width="33" class="preload" />

Include the array of preloading image elements to the bottom of the home page, just before the body tag. Placing the images at the bottom of the page requires the browser to load the entire page before preloading any of the images. Finally, simply use the same image path and name when referencing the preloaded images on subsequent pages. The browser will have cached the images and will be able to load them instantly. Remember not to use the preload class for images that are meant to be displayed.

Preloading Tuf with JavaScript

This method uses JavaScript to cache specified images as the document is loaded. Images will then be displayed immediately as they are called. The JavaScript itself degrades peacefully and has no effect on browsers that do not support JavaScript. The script is as follows. Simply replace ../path/to/image-0n.gif with the corresponding path and name of the image to be preloaded. Then, simply call the images as normal (e.g., <img src="../path/to/image-0n.gif" alt="Image Caption" />) wherever they are required.

<script>
<!--//--><![CDATA[//><!--

if (document.images) {

	img1 = new Image();
	img2 = new Image();
	img3 = new Image();

	img1.src = "../path/to/image-01.gif";
	img2.src = "../path/to/image-02.gif";
	img3.src = "../path/to/image-03.gif";

}

//--><!]]>
</script>

You can also wrap this method in a function like so:

function preloader() {
	if (document.images) {

		var img1 = new Image();
		var img2 = new Image();
		var img3 = new Image();

		img1.src = "../path/to/image-01.gif";
		img1.src = "../path/to/image-02.gif";
		img1.src = "../path/to/image-03.gif";
	}
}

It’s so much fun..

About the Author
Jeff Starr = Web Developer. Book Author. Secretly Important.
SAC Pro: Unlimited chats.

12 responses to “Preloading Images with CSS and JavaScript”

  1. The javascript code shown above only starts the image loading process. If you need to know when the browser is done caching the image then use the onLoad event for the Image Object.

    function loadImage(name){
    	image = new Image();
    	image.onLoad = imageLoaded(name);
    	image.src = name;
    }
    	
    function imageLoaded(name){
    	alert("Image Pre-Loaded " + name);
    }
  2. Perishable 2007/04/29 8:32 am

    Thank you, Mike! I am sure this information will prove useful. Cheers!

  3. thanks for the snippets. I was wondering if the 2nd method also works when the images are called in css as background image ?

  4. Perishable 2007/06/05 9:53 am

    alex,

    Excellent question. Thanks for the visit. I was not too sure about this myself, so I setup a test situation where a very large (over 1.4mb) file was to preload via the second method. I then setup a link:hover class to call the image via CSS background property. The idea was that if the large image is preloaded via JavaScript, there will be no delay when hovering over a link that requires it (as would be the case if the image was not preloaded). Anyway, the point is that, yes, method two indeed works for CSS background images. This fact may also be verified with the Firebug extension, which is an excellent Firefox web-development tool that will show the background image loading in “real time”. – Cheers!

    Addendum: After further testing of this method, it turns out that while current versions of Firefox, Mozilla, Opera, Netscape, Safari, Camino, and Flock all preload CSS background images via JavaScript, Internet Explorer 7 does not. Further, it would be safe to say that previous versions of IE also fail at preloading CSS background images.

  5. thanks for this tutorials..

    yeah this will be proven very usefull

  6. Exactly what I needed to preload my flash-show images!

    Thanks a lot.

  7. My pleasure, Juan! Thanks for the feedback :)

  8. thereby enhancing user experience.

    I don’t agree.

    By preloading images with this trick (or the new full css one), you with indeed make the images appear instantly later on, when the user will do some action that requires them, but as you load these images on page loading, you will have a much longer wait until the page is fully loaded.

    You are sacrifying first time loading performance for a better experience later.

    A method that would not increase first time loading, and would provide a better after-hand experience would be to load the images onload.

    The weak side of doing this is that if the user is too fast, your images might not be loaded yet, whereas with your method, they have to be loaded for the page to be ready.

    I use this technique on my blog. You can read what I wrote about it (maybe you’ll prefer the Google translated version), or just see it in action at the bottom of my source code.

    Anyway, I like your improved full css solution.

    Note : Google also has chosen to load some content onload.

  9. alexandre 2008/12/18 3:16 am

    i apologize for my unknowledge but i dont know where is the botton of the document please tell me thanks a lot

  10. Jeff Starr 2008/12/21 9:37 am

    @alexandre: the bottom of the document is generally the region just before the </body> and </html> closing elements. Check this article for more information.

  11. I used the 2nd method for css:hover images and it works wonderfully! Thank you SO much. You solved my headache!

    Kev

  12. @Kev: My pleasure! Glad to be of service! :)

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 »
Wizard’s SQL for WordPress: Over 300+ recipes! Check the Demo »
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.