1

I have a slideshow in the banner of my webpage. The images in this slide show can be somewhat large (>0.5MB). Because of this, I want to pre-load the images as much as possible. In an attempt to do this, I've written the following code:

var bgs = ["image1.png", "image2.png", "image3.png" ];
var bgi = 0;
var bgimg = null;

var isInitLoad = true;
$(document).ready(function () {
  $("#bannerTable").each(function () { $(this).fadeOut(15); });
  $("#bannerTable").fetchImage();
});

$.fn.fetchImage = function () {
  var image = bgs[bgi];
  var imageUrl = "/images/" + image;

  return this.each(function () {
    var $obj = $(this);
    $obj.fadeOut(250, function () {
    $obj.css('background', 'url(' + imageUrl + ')').fadeIn(250);

    bgi = bgi + 1;
    if (bgi >= bgs.length) {
      bgi = 0;
    }

    if (isInitLoad) {
      setInterval(getNextImage, 3000);
      isInitLoad = false;
    }
  });
});
}

function getNextImage() {
  $("bannerTable").fetchImage();
}

Unfortunately, my images are not being preloaded. How do I write my code such that: 1) The bannerTable fades in as soon as the first image is downloaded 2) Continue downloading the other images so they are pre-cached

Thank you so much for your help!

user70192
  • 13,786
  • 51
  • 160
  • 240

2 Answers2

1

Try this: Preloading images with jQuery

Community
  • 1
  • 1
Ciprian Mocanu
  • 2,166
  • 3
  • 25
  • 44
0

in fetchImage() try using Image object for precaching images.

DrStrangeLove
  • 11,227
  • 16
  • 59
  • 72