Preload images using css

qadenza picture qadenza · Jun 22, 2014 · Viewed 16.7k times · Source

Is this an acceptable way to preload images, compared to some js code inside of 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");

Answer

imbondbaby picture imbondbaby · Jun 22, 2014

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

This can be used to preload the images and swap them on hover. The "preload" div has no height/width since the images are set to background, so it doesn't show on the page, and the images are ready when you want to swap them on hover. (you will obviously have to set height/width on the anchors. I'm just showing minimal CSS here to get the point across)

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 post above shared a link that include many others.

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