Pre loading images with javascript, which is correct way to accomplish this?

1

I'm having problems uploading images to the server. I would like to know the correct way to preload those images.

// JavaScript Functions
function sleep (time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}

function load(){
    var colors = ["http://meusite.com/pasta/img/playerRightC.png","http://meusite.com/pasta/img/playerLeftC.png","http://meusite.com/pasta/img/playerRight.png","http://meusite.com/pasta/img/playerLeft.png","http://meusite.com/pasta/img/wallpaper01.png","http://meusite.com/pasta/img/cheese.png","http://meusite.com/pasta/img/toca.png","http://meusite.com/pasta/img/help1.png","http://meusite.com/pasta/img/help2.png","http://meusite.com/pasta/img/help3.png","http://meusite.com/pasta/img/cnImg.png"];

    for (color in colors) {
        var img = new Image();
        img.src = colors[color];
    }

}

load();

sleep(6000).then(() => {
    StartGame(); 
});;


window.addEventListener('keydown', KeyDown, true);

I added a delay of 6000ms to start the game, so images could be loaded by the load function.

However, the images are not preloaded, there is still a delay of 0.5ms to 2.0s on slower connections attempting to play the game. Is this correct for loading images? Is it a more effective way?

    
asked by anonymous 06.05.2018 / 20:23

1 answer

3

I do not think it's a good idea to try to guess the loading time of the images, as this can vary greatly depending on the connection, weight or quantity of images.

You can create img.onload for each image. In this way, the StartGame() function will only be called after all images have been loaded.

Create a counter starting at 0 , and as each image is loaded, it will increment the counter and when it is equal to the size of the array, the function is called:

function load(){
   var colors = ["http://meusite.com/pasta/img/playerRightC.png","http://meusite.com/pasta/img/playerLeftC.png","http://meusite.com/pasta/img/playerRight.png","http://meusite.com/pasta/img/playerLeft.png","http://meusite.com/pasta/img/wallpaper01.png","http://meusite.com/pasta/img/cheese.png","http://meusite.com/pasta/img/toca.png","http://meusite.com/pasta/img/help1.png","http://meusite.com/pasta/img/help2.png","http://meusite.com/pasta/img/help3.png","http://meusite.com/pasta/img/cnImg.png"];

   var num_imgs = colors.length; // conta a array
   var conta_imgs = 0; // contador
   for (color in colors) {
      img = new Image();

      img.onload = function(){ // evento onload
         conta_imgs++; // incrementa o contador quando uma imagem é carregada
         // quando forem iguais, chama a função
         if(conta_imgs == num_imgs) StartGame();
      }

      img.src = colors[color];
   }
}
    
06.05.2018 / 21:09