Paulo Gustavo
Paulo Gustavo

Reputation: 95

Preload image with Javascript and CSS

I have a big problem with images in javascript embedded aplications. I want make a preload image but I don't know how the browser works.

See this simple example: code

var colors = [
    "http://www.robolaranja.com.br/wp-content/uploads/2014/10/Primeira-imagem-do-filme-de-Angry-Birds-%C3%A9-revelada-2.jpg",
    "http://imguol.com/c/noticias/2013/12/13/13dez2013---esta-imagem-mostra-a-nebulosa-de-caranguejo-um-iconico-remanescente-de-supernova-na-nossa-galaxia-vista-do-observatorio-espacial-herschel-e-do-telescopio-hubble-uma-nuvem-de-gas-e-poeira-1386961235961_956x500.jpg",
    "http://wallpaper.ultradownloads.com.br/121350_Papel-de-Parede-Imagem-Abstrata_1920x1200.jpg"
]

var currentDiv = "div2";
var count = 0;
var lenght = colors.length;
var timeForNextImage = 0;
var preloadOk = false;

setInterval(function() {

    count ++;
    if (count > lenght) count = 0;

   var date = new Date();
   var time = date.getTime();

    if  (time > (timeForNextImage - 3000) && preloadOk == false) {
        preLoad();
    } else if (time > timeForNextImage) {
        play();   
    }



}, 300);

var play = function() {

    if (currentDiv == "div2") {
        $('#'+currentDiv).css("visibility", "visible");
    } else {
        $('#div2').css("visibility", "hidden");
    }
    var date = new Date();
    timeForNextImage =  date.getTime() + 10000;
    preloadOk = false;

    $("#lbl").text("div atual: "+currentDiv);
 };

var preLoad = function() {  

      if (currentDiv == "div1") {
        currentDiv = "div2";      
    } else {
        currentDiv = "div1";
    }

     $("#" + currentDiv).css("background-image", 'url('+colors[count]+')');
    preloadOk = true;
};

How you can look, I do a preload, in theory.. but, the browser only processes my image when I put it in the stage ?

What if I change the z-index attribute, it renders again?

Upvotes: 0

Views: 1133

Answers (2)

Shreyas
Shreyas

Reputation: 1462

A simple way to preload an image is to just create an image tag and set the url as the src. You don't have to attach it to the DOM to make the request.

var preLoad = function() {  
    var img = new Image();
    img.src = colors[count];
};

Upvotes: 1

Marcos Pérez Gude
Marcos Pérez Gude

Reputation: 22158

You return preloadOK = true but the image doesn't load. That's not a preloader.

To make a preloader you can play with new Image() object or with load() event.

var images = new Array()
function preload() {
  for (i = 0; i < preload.arguments.length; i++) {
    images[i] = new Image()
    images[i].src = preload.arguments[i]
  }
}
preload(
  "http://domain.tld/gallery/image-001.jpg",
  "http://domain.tld/gallery/image-002.jpg",
  "http://domain.tld/gallery/image-003.jpg"
)

See more

3 Ways to Preload Images with CSS, JavaScript, or Ajax

Upvotes: 2

Related Questions