Max Frai
Max Frai

Reputation: 64276

Preloading images with js

I used this tutorial to make image slider at my site. But I have more than 100 images. It will be hard to load everything when page loads. So, any tricks to preload first ~10 images, and when I'll slide to the 9th, for example, load another 10?

Or there is already-prepared plugin for jquery which provides this?

Upvotes: 1

Views: 191

Answers (2)

davidosomething
davidosomething

Reputation: 3437

with jquery, something as simple as this works:

$('<img />')[0].src = 'image.jpg';

it creates an element but never adds it to the page so the image is loaded, but never shown check the Net panel in firebug to see it loaded.

Upvotes: 1

Rich Bradshaw
Rich Bradshaw

Reputation: 72975

With jQuery I use this:

(function($) {
  var cache = [];

  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)

jQuery.preLoadImages("/images/img01.jpg","/images/img02.jpg");

Upvotes: 0

Related Questions