Preload images using css

Is this an acceptable way to preload images compared to some js code inside html / head

body:after{ display:none; content: url(img1.jpg) url(img2.jpg) ... } 

js way

 $.preload = function() { for (var i = 0; i < arguments.length; i++) { $("<img />").attr("src", arguments[i]); } } $.preload("img1.jpg","img2.jpg"); 
+7
css preload
source share
3 answers

I believe this method will work until the image is dynamically generated. The only problem with preloading using only CSS seems to be that the images are loaded using the page, not after it. You can fire the JavaScript event after pageload completes.

Further reading: http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

+3
source share

The concept is to place background images on a pseudo-element that is loaded when the page loads, but not displayed. This forces the browser to load images so that when they are called later by another element, they are ready to go.

This can be used to preload images and replace them on hover. The "Preload" div does not have a height / width, since the images are set to the background, so it does not appear on the page, and the images are ready when you want to change them on hover. (you obviously need to set the height / width on the anchors. I just show the minimal CSS here to get the point)

HTML:

 <div id="preload"></div> <div id="icons"> <a href="http://..." class="button-1"></a> <a href="http://..." class="button-2"></a> <a href="http://..." class="button-3"></a> </div> 

CSS

 #preload {background: url('pic1b.png'), url('pic2b.png'), url('pic3b.png');} .button-1 {background: url('pic1a.png');} .button-2 {background: url('pic2a.png');} .button-3 {background: url('pic3a.png');} .button-1:hover {background: url('pic1b.png');} .button-2:hover {background: url('pic2b.png');} .button-3:hover {background: url('pic3b.png');} 

Obviously, there are many other ways, and the message above shares a link that includes many others.

http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

+8
source share

In firefox, at least images are not cached with display: none . Instead, you can install:

 body:after { width: 0; height: 0; overflow: hidden; display: block; content: url('img1') url('img2') ...; } 
0
source share

All Articles