Cannot get image preloading to work correctly in I

2019-05-30 03:18发布

问题:

I'm working on an image slideshow that allows users to cycle through a set of images in semi-fullscreen. Here's a development version of it:

[link removed, was only temp link]

There are several ways to progress to the next image: by clicking the large image, by picking a specific thumb, by using the arrow icons or even your keyboard arrows. All of these basically call a js function loadImage with the correct params:

    function loadImage(id,url) {

        // general image loading routine

        // enable loader indicator
        $("#loading").toggle();

        var imagePreloader = new Image();
        imagePreloader.src = url;
        loading = true;
        $(imagePreloader).load(function() {

            // load completed, hide the loading indicator
            $("#loading").toggle();

            // set the image src, this effectively shows the image
            var img = $("#bigimage img");
            img.attr({ src: url });

            // reset the image dimensions based upon its orientation
            var wide = imagePreloader.width >= imagePreloader.height;
            if (wide) {
                img.addClass('wide');
                img.removeClass('high');
                img.removeAttr('height');
            } else {
                img.addClass('high');
                img.removeClass('wide');
                img.removeAttr('width');
            }

            // update thumb status
            $(".photos li.active").removeClass('active');
            $("#li-" + id).addClass('active');

// get the title from the active thumb and set it on the big image
var imgTitle = $("#li-" + id + " a").attr('title');
log(id + ":" + imgTitle);
        $(".caption h1").text(imgTitle);

        // loading routine completed
        loading = false;

        //return true;
        });
}

There's a lot of stuff in there not relevant for the question, but the focus is on the actual preloading and showing of the requested image. The whole is working perfectly in both Firefox and Chrome, yet in IE8 nothing happens. Oddly, it does work the first time I click on the next arrow or use the keyboard arrow, after that it simply fails.

I'm having a tough time debugging this. In stepping through the code I see that the load event handler is never actually called, despite being sure that the URL passed in is correct. I've tried with imagePreloader.onLoad (without the jQuery) but that has no effect either. I'm stuck debugging this and understanding why it works the first time.

回答1:

It sounds like it is due to image caching. In some cases the .load() fails to fire the event-handler when the image is cached in your browser cache. See this post on the issue.

See the $.fn.imagesLoaded jQuery plugin.