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)?
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)?
Share Improve this question edited Nov 10, 2015 at 15:21 sjkm 3,9372 gold badges26 silver badges43 bronze badges asked Oct 31, 2013 at 22:22 MattMatt 351 gold badge1 silver badge7 bronze badges 1- This is pretty much a duplicate question. No need for jQuery to preload images. A simple search here will find you dozens of posts on this topic. Here's one that will even call you back when they're all loaded: Image preloader javascript that supports events – jfriend00 Commented Oct 31, 2013 at 22:33
3 Answers
Reset to default 11You 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>
The easiest way to preload an image would be something like this:
function preload(selector, url) {
$('<img/>').attr({
src: url,
height: '1px',
width: '1px'
}).appendTo($(selector)).delay(1000).remove();
}
I did it like this.
I looked up any hover state images then preloaded the hover state by replacing the -nm (normal) with the -hv (hover)
The beauty of doing it like this is that there is no hard coding of URLs
$(function() {
$(this).find("img[src*='-nm']").each(function () {
$('<img/>')[0].src = this.src.replace(/-nm/, "-hv");
});
})