mercredi 16 mai 2018

Image preloading working in Safari but not in Chrome

My goal is to preload images that are in an array and then display a random image instantly on the click of a button. On the next click another random image from the array should appear. Here is the code:

let randomImage = new Array(24);

function preload() {
    for (let x = 1; x < randomImage.length; x++) {
    randomImage[x] = "img/img" + x + ".jpg";
    }
    for (let i = 1; i < randomImage.length; ++i) {
    let img = new Image();
    img.src = randomImage[i];
    }
}

function randomImg() {
    let random = Math.floor(Math.random() * randomImage.length);
    if (random === 0) {
    return randomImage[1];
    }

document.getElementById("img_placeholder").src = randomImage[random];

}

What this is supposed to do is first preload the array with images (the preload() function).

Then the randomImg() function is called everytime a button is pressed. This works fine for safari, but in chrome it first preloads all images correctly but then when I click the button to go to the next random image it sends another get request to load the image again, oposed to in safari where it just takes the loaded image.

What am I doing wrong here?




Aucun commentaire:

Enregistrer un commentaire