Radley Sustaire
Radley Sustaire

Reputation: 3399

Javascript image preloading, I'm doing something wrong

I'm using document.images to load images when a visitor first visits the website. The reason is because I have a few different areas which have rollover images. Before I switch over to using CSS sprites (modifying a lot of work), I'm going to ask here.

So I'm preloading images with this:

images = new Array();

if (document.images) {
    images.push(preloadImage("http://website.com/images/myimg.png", 300, 200));
}

function preloadImage(src, x, y) {
    var img = new Image(x, y);
    img.src = src;
    return img;
}

And according to Chrome's "resource" panel, this is working just fine. Even after pressing CTRL+F5, the images listed in the JS are downloaded.

HOWEVER, they are not used. If I hover over an element in one of my three scripts, the image is downloaded a second time. Derp?

I assume that when preloading images this way, you're supposed to put that image array to use. I thought the browser would be smart enough to say "Hey, this is the same image, let's use it twice" but apparently not.

So is this correct? Do I need to rewrite my programs to preload images individually? I know it doesn't sound hard, but it's really not designed for that.

Upvotes: 2

Views: 280

Answers (2)

frank_neff
frank_neff

Reputation: 1012

This works fine for me:

    function imgPreload() {
        var imageList = [
            "my/firstimage.png",
            "my/secondimage.jpg",
            "my/thirdimage.png"
        ];
        for (var i = 0; i < imageList.length; i++ ) {
            var imageObject = new Image();
            imageObject.src = imageList[i];
        }
    }

    imgPreload();

Cheers. Frank

Upvotes: 1

Jan Aagaard
Jan Aagaard

Reputation: 11184

This is not really an answer to your question, but I proprose a different solution. Put all the images you need to preload inside a div that is hidden from the user. I know, I know, this i not as elegant, but it should work just fine. :)

<div style="display: none;">
    <img src="http://website.com/images/myimg.png" alt=""/>
    ...
</div>

Upvotes: 2

Related Questions