Question

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

Was it helpful?

Solution

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>

OTHER TIPS

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");
        });
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top