Dan
Dan

Reputation: 12096

jQuery slideshow loop with asynchronously loaded images

I'm trying to create a simple jQuery slideshow that doesn't load all of the images at start, the next image to be used will instead be loaded asynchronously to reduce the page size.

I have the slideshow working but the preload of the next image doesn't seem to be fully functioning?

Exaple jQuery

var i = 2;
var total = 9;

var obj = setInterval(function(){    

    $(".slides_container img").fadeOut("slow", function(){
        $(this).attr("src" ,"/images/slide-" + i + ".jpg").load(function() {
            $(this).fadeIn();
        });
    });

    if(i < total){
        i++;
        //Preload Next Image
        (new Image()).src = "/images/slide-" + i + ".jpg";
    }
    else   
        i = 1;
}, 4000);

Possible Cause of the Issue

The line underneath the preload comment must load the next image however the code highlighted below seems to not use any cached images but instead pull them from the server again?

I've had to use the .load() to make the .fadeIn() work correctly

$(this).attr("src" ,"/images/slide-" + i + ".jpg").load(function() {
    $(this).fadeIn();
});

Upvotes: 0

Views: 1000

Answers (1)

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114367

$(this).attr("src" ,"/images/slide-" + i + ".jpg").load(function() {
    $(this).fadeIn();
});

Should be:

$(this).load(function() {
    $(this).fadeIn();
});

$(this).attr("src" ,"/images/slide-" + i + ".jpg")

Or try: :

$(this).onload = function () {
   ....
})

Upvotes: 2

Related Questions