1

I created site with changing background images.
HTML:

<div id="templatemo_header">
</div>

CSS:

#templatemo_header {
    background: url(images/templatemo_header.jpg) no-repeat;
}

And JS code which changes the BG image each 3 seconds

function displayImage(image) {
    document.getElementById("templatemo_header").style.backgroundImage = image;
}

function displayNextImage() {
    x = (x == images.length - 1) ? 0 : x + 1;
    displayImage(images[x]);           
}

function displayPreviousImage() {
    x = (x <= 0) ? images.length - 1 : x - 1;
    displayImage(images[x]);           
}

function startTimer() {
    setInterval(displayNextImage, 3000);
}

var images = [], x = -1;
images[0] = 'url("images/templatemo_header1.jpg")';
images[1] = 'url("images/templatemo_header2.jpg")';
images[2] = 'url("images/templatemo_header3.jpg")';
images[3] = 'url("images/templatemo_header.jpg")';

The problem is when each of BG images changed only first time, image dissapeares and after some moment new image appears.
I guess, it's because new BG image is downloaded.
Is it some way to force download the images immediately, say in function startTimer?
Thanks in advance.

Felipe Miosso
  • 7,309
  • 6
  • 44
  • 55
Costa Mirkin
  • 947
  • 3
  • 15
  • 39
  • Possibly this link can help you http://stackoverflow.com/questions/476679/preloading-images-with-jquery – Nazar Harasym Jan 14 '14 at 22:43
  • 3
    Don't put tags in the question title. I've fixed it for you, but as this is your **33rd** question, you should be used to how things work by now. – T.J. Crowder Jan 14 '14 at 22:45

1 Answers1

2

There are a few ways to pre-load images using javascript here. By pre-loading the images you may have better luck when displaying them. In your case I would use Method 3 if possible, if not Method 2. As described in the article, you would use the window.onload event to kick off the downloading of the images once the page has loaded.

I would just setup your image array as follows:

window.onload = preLoadImages();

function preLoadImages(){
    preLoadImage = new Image();

    images[0] = "images/templatemo_header1.jpg";
    images[1] = "images/templatemo_header2.jpg";
    images[2] = "images/templatemo_header3.jpg";
    images[3] = "images/templatemo_header.jpg";

    for(i=0, i<=images.length, i++){
        preLoadImage.src=images[i];
    }
}
puddinman13
  • 1,408
  • 4
  • 18
  • 35
  • 1
    Answers should contain at least a summary of what is found at the link. Link only answers are frowned upon here: http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers – Katie Kilian Jan 14 '14 at 22:48
  • More details have been added. – puddinman13 Jan 14 '14 at 23:02