2

This code switches the background between two different images. However when it switches from the first image to the second there is always a one second buffer before the image gets displayed and this only happens the very first time the images switch. How can I get rid of the buffer?

function changeBgColor(){
   var img = ['url(img/mechanic.jpg)', 'url(img/start.jpg)'];
   var nImg = img.length;
   var currentImg = 0;
   document.body.style.backgroundImage = "url(img/start.jpg)";
   document.body.style.backgroundSize = "cover";
   document.body.style.backgroundRepeat = "no-repeat";
   var imgChange = setInterval(function(){
        document.body.style.backgroundImage = img[currentImg];
        document.body.style.backgroundSize = "cover";
        document.body.style.backgroundRepeat = "no-repeat";
        if(currentImg == nImg-1){
            currentImg = -1;
        }
        currentImg++;
   },10000);
}
cweiske
  • 30,033
  • 14
  • 133
  • 194
  • Load both images onto the page, but keep them hidden. This will cache the resource when the page loads. – Ethan Jul 08 '14 at 19:32
  • 1
    This question may help you out a bit. http://stackoverflow.com/questions/21125544/download-changing-background-images-immediately?rq=1 Basically, you just need to preload your image before switching to it – Meg Jul 08 '14 at 19:32

3 Answers3

2

This will be due to the loading of image. Once the image is loaded it is cached and therefore the problem is not evident after first load. To combat this you could preload the images in question using CSS or jquery

CSS

body:after{
    display:none;
    content: url(img01.png) url(img02.png) url(img03.png) url(img04.png);
}

jQuery

<script>
  pic = new Image();
  pic2 = new Image();
  pic3 = new Image();
    pic.src="images/inputs/input1.png";
    pic2.src="images/inputs/input2.png";
    pic3.src="images/inputs/input3.png";
</script>
Kevin Lynch
  • 24,427
  • 3
  • 36
  • 37
0

It will be due to the image needing to load. The second time it switches the browser has already stored it in the cache. You need to let the image load before displaying it.

Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
0

Can you put the two images into separate divs, and toggle making one visible / the other hidden? That should remove the delay when you switch between the two.

Geremy
  • 2,415
  • 1
  • 23
  • 27