I previously asked a question on how to hover on a small image and load an additional image to the right side of the page. I have everything working correctly, but now I want to preload images.
How can I preload an image using JQuery so that I can show it immediately to the user when I want to (without a loading time)?
You can preload an image quite easily as follows:
using JQuery
function preloadImg(src) {
$('<img/>')[0].src = src;
}
preloadImg('http://yoururl/to/the/picture.jpg');
or Native Javascript
function preloadImg(src) {
var img = new Image();
img.src = src;
}
preloadImg('http://yoururl/to/the/picture.jpg');
or Using CSS (no JavaScript required)
You can also preload images using CSS (and HTML)
CSS:
div#preload { display: none; }
HTML:
<div id="preload">
<img src="http://yoururl/to/the/picture1.jpg" width="1" height="1" alt="Image 1" />
<img src="http://yoururl/to/the/picture2.jpg" width="1" height="1" alt="Image 2" />
<img src="http://yoururl/to/the/picture3.jpg" width="1" height="1" alt="Image 3" />
</div>