0

I am using following script to show background image for a div element.

Problem with this is that images are large around 1MB each and they don't quickly so that background effect can be smooth. I wrapper function in `$(window).load(function () {}); but it didn't made any difference.

how can i delay background image download so that it only starts when all images are downloaded.

jQuery(function ($) {
  var body = $('.hmcarousel');
  var backgrounds = new Array(
    "url(soml_slider_1.jpg)",
    "url(soml_slider_2.jpg)",
    "url(soml_slider_3.jpg)",
    "url(soml_slider_4.jpg)",
    "url(soml_slider_5.jpg)"
  );
  var current = 0;
  function nextBackground() {
    body.css(
      'background',
      backgrounds[current = ++current % backgrounds.length]
    );
    setTimeout(nextBackground, 5000);
  }
  setTimeout(nextBackground, 5000);
  body.css('background', backgrounds[0]);
});
Learning
  • 19,469
  • 39
  • 180
  • 373

1 Answers1

1

I believe answer for your question is in this thread.

Another option is to trigger the onload and/or onerror events by creating an in memory image element and setting its src attribute to the original src attribute of the original image. Here's an example of what I mean:

$("<img/>")
    .load(function() { console.log("image loaded correctly"); })
    .error(function() { console.log("error loading image"); })
    .attr("src", $(originalImage).attr("src"))
;
Community
  • 1
  • 1
IAfanasov
  • 4,775
  • 3
  • 27
  • 42