Bailz
Bailz

Reputation: 615

Javascript reloading preloaded image

The following piece of Javascript is intended to preload an image, set a div's background to the image and then fade the whole div in...

$("<img/>")
    .attr("src", "../services/imageResize.php?img=" + img + "&width=150")
    .load(function(e){
        $("<div/>", {
            class: "smallThumb"
        })
        .css("background", "url(" + $(this).attr("src") + ") no-repeat center center")
        .appendTo(images)
        .fadeIn(500);

        if(count == imgTotal)
        {
            loadingImages = false;
            images.css("background","#fff");
        }
    });
count++;

I've tested it in Chrome and Safari; both fade the div in and then finish loading the image. I'm perplexed as to what is causing it to reload the image for the .css statement.

Upvotes: 1

Views: 395

Answers (3)

Bart
Bart

Reputation: 17371

I think your problem is that the onload event fires before the image is fully loaded. If you're assuming the image is fully loaded it will appear like it's reloading.

The img.onload will trigger whenever the bowser is ready to render the image. It is no garantie that the image will be fully loaded. The only way to test if an image is fully loaded is with the img.complete attribute.

Some time ago I answered to the question How to monitor an image source for fully loaded status

After the answer I wrote a little jQuery plugin which utilizes the complete attribute.

You could use it like e.g.

$(function () {
    $.preload('your-image.png').progress(function (img) {
        // set background
        $('body').css('background', 'url(' + img.src + ')');
    });
});

Upvotes: 0

Judson Terrell
Judson Terrell

Reputation: 4306

Have you tried hardcoding the image into the page hidden and seeing what happens? Part of the issue is that you are passing URL params which could be making the images unique to each other.

Upvotes: 0

Ted Johnson
Ted Johnson

Reputation: 4343

The are two different things. HTML DOM and CSS, it will load it twice. They both don't really know about each other. Just because you use the same src "string" does not mean they use the same src image content. I would test it out with the image src set to a single pixel type of thing and then load the background. This is a well documented approach to CSS backgrounding images. Also caching can help it at least not request it twice from the server. A good thing to do anyhow.

Upvotes: 0

Related Questions