Search code examples
jqueryimagecachingcycle

Cycle through a set of multiple images with jquery in an endless loop?


I have this jquery image cycler that does the following:

  • preload multiple images ( say 50? )
  • Pick random from these 40 and assign 14 of them to 14 div's each time
  • cycling them forever

What would be the best way to cycle through 14 images, getting a random image assigned to each of the 14 divs?

EDIT: AJAX calls like my first solution seems a stupid idea ( high load on server if there are hundreds of pages open ) so precaching seems a better option.

EDIT2: Rewrote the question to be more precise and clear

I found this great method on pre-caching:

  var images = [
    '/path/to/image1.png',
    '/path/to/image2.png'
];

$(images).each(function() {
    var image = $('<img />').attr('src', this);
});

My old current method:

  $("#hi1").load('/get_img');
  $("#hi2").load('/get_img');
  $("#hi3").load('/get_img');
  ... etc till 14

  var refreshId = setInterval(function() {
      $("#h1").load('/get_img');
      $("#h2").load('/get_img');
      $("#h3").load('/get_img');
      }, 4000);
      $.ajaxSetup({ cache: true });
  })

Solution

  • You could just return the source in the AJAX and create an <img> and set the src, and then if it's not needed, hide it, so if that image gets returned again, you can just unhide it instead of loading it again. You can check to see if the image exists with something like:

    $('img[src="' + src + '"]').length > 0;
    

    If that's true, then it exists, so just show it. If not, load the image into the DOM. Just hide images when not needed.