1

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/

  • well, you're *loading* images, but *pre-loading* images requires that you load them before they are needed. the css will load the images, unless you're going to wait for javascript to load them before loading the css this isn't going to do anything. – I wrestled a bear once. Aug 29 '19 at 15:10
  • also, this really has nothing to do with jquery whatsoever. you will probably get more attention if you use the javascript tag instead. – I wrestled a bear once. Aug 29 '19 at 15:12

2 Answers2

0

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>
Patrik Alexits
  • 987
  • 9
  • 24
0

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?