0

For a sort of slideshow I'm trying to implement a clever image pre-loader, which should work as following:

  1. On load of slideshow first image is shown and images start loading in background in order 2, 3, 4, ...
  2. If user decides to switch to image n (which can be done via search or thumbs or ...) and the triggered preload (from 1.) didn't load n yet, the order (2, 3, 4, ...) established in 1. will be re-organized with n as first element.

Other possibility for 2. could be to suspend preloading, load image n, and continue preload, but I'd prefer first idea because this will give you the freedom of more sophisticated re-ordering, e.g. (n, n+1, n+2, ..., last, 1st-not-loaded, 2nd-not-loaded, ...).

So far I just did a simple preload-loop like that:

for (var i = 0; i < issue.pages.length; i++)
{
  log("preloading image from URL " + issue.pages[i].imageUrl);
  var img = new Image();
  img.onload = function()
  {
    log("reading loading image " + this.src);
  };
  img.src = issue.pages[i].imageUrl;
} 

which works fine, but seems to block downloading of other images: If I call

imageN = new Image();
imageN.src = issue.pages[n].imageUrl;

somewhere else (onClick of thumb) while images of loop still loading, imageN will not be loaded before it's its turn from order in loop.

Any ideas?

Kai Huppmann
  • 10,705
  • 6
  • 47
  • 78

2 Answers2

1

To my knowledge there is no way to stop or suspend an image loading with javascript. However, a neat way to control the order of the images loading would be to chain together their load events. Here is an example (using jQuery).

In the example I have an array imgQueue that I am using as a queue and a function loadNextImage that grabs an image off the queue to load and calls loadNextImage when the image is done loading.

function loadNextImage() {
    if (imgQueue.length > 0) {
        var imgN = new Image();
        imgN.src = imgQueue.shift();
        $(imgN).load(function(){
            $("#main").append(imgN);
            loadNextImage();
        });
    }
}

To change the order images are loading you would literally just move them ahead in imgQueue, for example if I wanted to move image 5 to the front:

imgQueue.unshift(imgQueue.splice(4,1));

This isn't perfect, for instance, unless the images are large it probably makes more sense to load them in groups. Also because loadNextImage manipulates the queue you can't keep track of images just by their original index, you'd need to do something fancy like store them as hashes so you can find them later:

var imgHashQueue = [
   {name: "name", url = "url"},
   ...
]
nwellcome
  • 2,279
  • 15
  • 23
0

Couple resources here: http://ditio.net/2010/02/14/jquery-preload-images-tutorial-and-example/ - http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript

Previous SO discussion: Preloading images with jQuery

Community
  • 1
  • 1
Savino Sguera
  • 3,522
  • 21
  • 20