views:

26

answers:

1

There are plenty of gallery plugins out there that rotate images but they all seem to use a list of images on a page so initially they all have to be downloaded. if this happens at the top of a page then it can slow down load time a lot especially if the images are large or there are a lot of them.

I am looking to rotate images based on a list of links instead where the image is loaded as it is needed in rotation? I have searched Google with no luck - anyone find or have something like tthis?

A: 

All these sorts of scripts use images loaded on the page for a very good reason - your user will end up with a blank space where the image should be when it rotates, until it has been downloaded.

You could always put the images at the very end of the page in a hidden container and/or with a width and height of 1 pixel. Users shouldn't notice the delay in downloading these images because they're at the very end of the page, although if you have any scripts running on page load then these will be delayed until the images have downloaded.

If you do want to go ahead with this and you cannot find a custom plugin out there, you can do this in a few lines of JavaScript - with only one line of jQuery. This will probably not be valid JavaSscript so it may take a bit of coaxing to get it to work; it's more showing you the theory.

var numberOfImages = 3;
var lastImageIndex = -1;
Array imageUrls[numberOfImages];
imageUrls[0] = 'http://www.mysite.com/image1.jpg';
imageUrls[1] = 'http://www.mysite.com/image2.jpg';
imageUrls[2] = 'http://www.mysite.com/image3.jpg';

function rotateImage()
{
    // Variable for our current number
    lastImageIndex++;

    // Roll round
    if (lastImageIndex > numberOfImages)
    {
        lastImageIndex = 0;
    }

    // Update our image's src tag (requires an id="imageTag" attribute on the <img> tag)
    $('#imageTag').attr('src', imageUrls[imageNumber]);
}

// Rotate every 2 seconds
window.setInterval(rotateImage, 2000);

// Set initial image now
rotateImage();
Andy Shellam