Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - Preload Images (using JQuery / native JavaScript / CSS)

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)?

like image 910
Matt Avatar asked Aug 03 '26 23:08

Matt


1 Answers

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>
like image 79
sjkm Avatar answered Aug 06 '26 11:08

sjkm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!