Archive: Preloading Images with CSS
AttentionThis post is an archived post. This means it is old or has been archived for rewriting in the near future. Please be aware that the contents of this article or page may be out of date. If you need assistance be sure to leave comments and our community can help you.
Add the following code after the body tag:
Add the following to your stylesheet:
Place all of the images that you want to be preloaded inside the preloader wrapper. These images will load when the page loads but will not be visible anywhere on the page.
The trick behind this workaround is using stylesheets to hide our preloader wrapper from view. The wrapper's size ensures all browsers will load its contents and the overflow setting ensures only the one pixel is visible at any time. The images will still load as browsers will assume they are visible which will prevent the need to load the images when they are needed.
Placing the wrapper one pixel above the top most margin of the body will mean the single pixel is hidden outside of view and outside the margin of the one side of the page that will not cause a scrollbar.
As the images have loaded when the relevant hover effects or whatever purpose the images will be used for is called upon, they will display instantly, having been preloaded by our little trick. If you didn't preload images then some graphical templates with a lot of hover effects would display incorrectly at times. If the images that appear when one hovers over are moderately large the hover effect may be lost in the impatience of users: by the time the image has fully loaded they will have moved to the next page or moved their mouse from the link or element causing the hover effect.
Putting the wrapper at the start of your source will cause higher loading times on pages where you are preloading a lot of images. This workaround is not intended for large images or a large amount of images. If you need to preload several images, however, you can move the wrapper to before the end of your source. This will put the images last in the parsing order but still ensure they are preloaded.
It should be noted that this workaround will only work on images.