TarranJones
TarranJones

Reputation: 4242

smart image loading with javascript

Heres is my scenario, We have a main image of a cat(lets say its 1000px by 1000px) and 10 thumbnail images of cats(100px by 100px). when the thumbs are selected the main image changes. At the moment the images are being preloaded using

$('#showcase .thumbnail').each(function(index,el){
    var mainImg = $(el)[0].src.replace('small','large');
    var img = new Image();
    img.src = mainImg;
}); 

this will load my large versions of the thumbnail images.

I have A <select> tag, with four <option>'s, when an option is selected the 10 thumbnail images will change as well as the main image. The user has no interest in cats and selects the dogs option almost immediately.

THE Question

Can the cat images be pushed to the back of the list of images to download and prioritise the dog images?

Thanks in advance.

Upvotes: 1

Views: 312

Answers (1)

Reeno
Reeno

Reputation: 5705

Let's suppose the select looks like this:

<select id="select">
    <option value="">Please select</option>
    <option value="dogs">Dogs</option>
    <option value="cats">Cats</option>
    <option value="fishes">Fishes</option>
</select>

And every image has a class name corresponding to the values (e.g. <img class="cat" src=... />) Then here's some code (didn't test it thoroughly):

// is something selected in the dropdown
var selection = false;
// observe the dropdown
$('#select').change(function(){
    // the user selected something -> store it
    if(this.value) {
        selection = this.value;
    }
    // back to default
    else {
        selection = false;
    }
});

// store the images
var images = $('#showcase .thumbnail');
// stack for the unreplaced images
var stack = [];

// first run
function replaceImages(images, currentIndex) {
    // we're finished
    if (imageURLarray.length == 0 || images.length == currentIndex) {
        return false;
    }

    // there's no selection at all or we have a selection and the current image has the corresponding class -> replace it
    if(!selection || (selection && $(images[currentIndex]).hasClass(selection))) {
        var mainImg = $(images[currentIndex])[0].src.replace('small','large');
        var img = new Image();
        img.src = mainImg;
        // wait for loading. If we wouldn't wait, all image src's would be replaced in a second and our prioritizing magic wouldn't happen
        img.onload = function(e){
            // image has loaded -> next image
            replaceImages(images, currentIndex++);
        }
    }
    // there's a selection and the class doesn't match -> store the image in the stack
    else {
        stack.push(currentIndex);
    }
}

// run the function
replaceImages(images, 0) {

// process the stack, i.e. the non-replaced images
$(stack).each(function(index, val){
    var mainImg = $(images[val]).src.replace('small','large');
    var img = new Image();
    img.src = mainImg;
});

Upvotes: 1

Related Questions