2

I am using Jquery to alter the source of an image as the page scrolls. However, currently they are loading as they are displayed and i would like to have them preload several images prior to being shown.

HTML

<img src="/img/1.jpg" />

JQuery

$(window).load(function(){
// Array of images to swap between
var images = [/img/1.jpg, /img/2.jpg, /img/3.jpg, /img/4.jpg];

var totalImages = images.length; 

var documentHeight = $(document).height();

// Work out how often we should change image (i.e. how far we scroll between changes)
var scrollInterval = Math.floor(documentHeight / totalImages);

$(document).scroll(function () {
// Which one should we show at this scroll point?
i = Math.floor($(this).scrollTop() / scrollInterval);
// Show the corresponding image from the array
$('img').attr('src', images[i]);
});
});//]]>  

css

img {
position: fixed;
top: 0;
left: 0;
height: 100%;
}
body {
height: 5000px;
}

Attempt. I would like to add something similar to this to,

$(document).scroll(function () {    
    function preload(arrayOfImages) {
        $(arrayOfImages).each(function(){
            (new Image()).src = this;
        });
    }

    i = Math.floor([i]+'1');

    preload([[i]]);
}

But cannot figure how to code it... (New to JS)

Brigand
  • 84,529
  • 20
  • 165
  • 173
user1949366
  • 465
  • 2
  • 6
  • 17

1 Answers1

0

Inside your loop.

var nextTenImages = images.slice(i, i+10);    
// preload the next image
preload(nextTenImages);

JSFiddle: http://jsfiddle.net/gvee/ygkWH/8/

EDIT: Credit to the following SO topic for preloading images: Preloading images with jQuery

Community
  • 1
  • 1
gvee
  • 16,732
  • 35
  • 50