Posted By

JimSangwine on 05/05/11


Tagged


Versions (?)

CSS Only Image Preloading


 / Published in: CSS
 

  1. /*
  2. One big reason to use image preloading is if you want to use an image for the background-image of an element on a mouseOver or :hover event. If you only apply that background-image in the CSS for the :hover state, that image will not load until the first :hover event and thus there will be a short annoying delay between the mouse going over that area and the image actually showing up.
  3. Technique #1
  4.  
  5. Load the image on the element's regular state, only shift it away with background position. Then move the background position to display it on hover.
  6. */
  7.  
  8. #grass { background: url(images/grass.png) no-repeat -9999px -9999px; }
  9. #grass:hover { background-position: bottom left; }
  10.  
  11. /*
  12. Technique #2
  13.  
  14. If the element in question already has a background-image applied and you need to change that image, the above won't work. Typically you would go for a sprite here (a combined background image) and just shift the background position. But if that isn't possible, try this. Apply the background image to another page element that is already in use, but doesn't have a background image.
  15. */
  16.  
  17. #random-unsuspecting-element { background: url(images/grass.png) no-repeat -9999px -9999px; }
  18. #grass:hover { background: url(images/grass.png) no-repeat; }
  19.  
  20. /*
  21. The idea create new page elements to use for this preloading technique may pop into your head, like #preload-001, #preload-002, but that's rather against the spirit of web standards. Hence the using of page elements that already exist on your page.
  22.  
  23. I had the idea to try to and use the same element, only use the :after pseduo-class to load the image, so you didn't need to rely on there being enough extraneous background-free images on your page to work with, but for whatever reason didn't want to preload them properly.
  24. */

Report this snippet  

You need to login to post a comment.