Is it correct way to preload img to display div background?

63 Views Asked by At

Hi I'm using this code to preload some images that I use as a background for some divs.

I visualized the chrome console and actually the preload works but it seems to me that anyway when I start the application there is a flickering on the div in question, as if the call of the image css was independent of the preload made of it.

It is my impression? did I miss anything in the preload method?

in jquery i use:

$(window).load(function () {

let p_url = cc_object.p_url;
p_url = p_url + '/public/images/';

let cache = [];

$.preLoadImages = function () {
    let args_len = arguments.length;
    for (let i = args_len; i--;) {
        let cacheImage = document.createElement('img');
        cacheImage.src = arguments[i];
        cache.push(cacheImage);
    }
};
$.preLoadImages(
    p_url + "dorso.png",
    p_url + "t-z-amore-bg.jpg"
);
});

while in css:

.cont_game  {
    background: url(../images/t-z-amore-bg.jpg) no-repeat center center;
}    
.cont_game .carta_estratta.empty {
    background: url(../images/dorso.png) no-repeat center center;
}

you can see it in action at https://www.casadeicartomanti.it/tarocchi/tarocchi-online/

2

There are 2 best solutions below

0
Patrik Alexits On

You are detecting the change on the needed input, then you call the readURL() function:

$('body').on('change', '[name="pic_path"]', function () {
    $('.preview').css('background-image','');
    readURL(this);
});

In the readURL() you are inserting the selected image in to a div as a background:

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function (e) {
        $('.preview').css('background-image','url(' + e.target.result + ')');
    };
    reader.readAsDataURL(input.files[0]);
  }  
}

Then you are just placing the given HTML element somewhere where you want and the selected picture will be previewed in it.

<div class="preview"></div>
0
Paolo Battiloro On

so my method is not right? once the images have been preloaded, shouldn't the browser load the ones I said to preload as background?