Preloading Image Bug in IE6-8

Posted by Kevin C. on Stack Overflow See other posts from Stack Overflow or by Kevin C.
Published on 2010-04-15T23:52:56Z Indexed on 2010/04/16 0:03 UTC
Read the original article Hit count: 219

Page in question: http://phwsinc.com/our-work/one-rincon-hill.asp

In IE6-8, when you click the left-most thumbnail in the gallery, the image never loads. If you click the thumbnail a second time, then it will load. I'm using jQuery, and here's my code that's powering the gallery:

$(document).ready(function() {
// PROJECT PHOTO GALLERY
var thumbs = $('.thumbs li a');
var photoWrapper = $('div.photoWrapper');

if (thumbs.length) {
    thumbs.click( function(){
        photoWrapper.addClass('loading');

        var img_src =   $(this).attr('href');

        // The two lines below are what cause the bug in IE. They make the gallery run much faster in other browsers, though.
        var new_img =   new Image();
        new_img.src =   img_src;

        var photo =     $('#photo');
        photo.fadeOut('slow', function() {
            photo.attr('src', img_src);
            photo.load(function() {
                photoWrapper.removeClass('loading');
                photo.fadeIn('slow');
            });
        });

        return false;
    });
}
});

A coworker told me that he's always had problems with the js Image() object, and advised me to just append an <img /> element inside of a div set to display:none;, but that's a little messy for my tastes--I liked using the Image() object, it kept things nice and clean, no unnecessary added HTML markup.

Any help would be appreciated. It still works without the image preloading, so if all else fails I'll just wrap the preloading in an if !($.browser.msie){ } and call it a day.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery