Friday, September 25, 2009

Preload Images the Right Way

Sure, all of us cringe a little when we see that phrase. Even so, for things like overlaysof which modals and tooltips are memberspreloading the background images is a reasonable thing to do. (I still don't fully endorse it, more on that later.)1.

I tried this preload code:


(function(){
    var i, img, imageLoader = {
        imagesToLoad: [
            'resources/css/images/btn-default-sprite.png',
            'resources/css/images/bg-tooltip-left.png',
            'resources/css/images/bg-tooltip-right.png',
            'resources/css/images/bg-tooltip-image-left.png',
            'resources/css/images/bg-tooltip-image-right.png'
        ],
        loadedImages: []
    };
    for(i in imageLoader.imagesToLoad){
        img = new Image();
        img.src = imageLoader.imagesToLoad[i];
        imageLoader.loadedImages.push( img );
    }
})();

The images didn't seem to be loading any sooner though. So I put a tracer in the list - an image source reference that I knew didn't exist. Then I fired up the page and looked at fiddler. (I would've looked at firebug's net tab, but I was troubleshooting IE6 specifically.) No 404s. So then I tried this code:


(function(){
    var imagesToLoad = [
        'resources/css/images/btn-default-sprite.png',
        'resources/css/images/bg-tooltip-left.png',
        'resources/css/images/bg-tooltip-right.png',
        'resources/css/images/bg-tooltip-image-left.png',
        'resources/css/images/bg-tooltip-image-right.png'
    ];
    $('<div class="no-print" style="position:absolute;left:-9999px"/>')
        .appendTo('body')
        .html('<img src="'+imagesToLoad.join('"/><img src="')+'"/>');
})();

And I got my 404.

For the purposes of this discussion, preloading doesn't mean loading the images before the rest of the page, it means loading them before they're used.

No comments:

Post a Comment