0

I am trying to change the background image of div using the following script:

  $.fn.preload = function() {
                          this.each(function(){
                         $('<img/>')[0].src = this;
                        });

                }
$(document).ready(function(){
           var images = [];
           for( var i=0; i<8; i++){
                images[i] = 'imgs/'+i+'.png';
           }
           $(images).preload();
            var i = 0;
                setInterval(function(){
                $('.header').css({'background-image':'url(imgs/'+i%8+'.png)'});
                i++;
            }, 700);
    });

but the images flicker on both chrome and firefox on change, how tp solve this?

markpmark
  • 51
  • 4

1 Answers1

0

The browser needs to make a new request to fetch the image and it will flicker while the browser makes that request, for your preload to work, which you seem to know from the preload image, but without attaching the image into the dom, normally it won't request it. I would rewrite your function to something similar to this. As mentioned in this answer.

preloadImages(images) {
    images.forEach((url) => {
       var img=new Image();
       img.src=url;
    }
}
Dvid Silva
  • 1,110
  • 13
  • 25
  • I have 8 images, in firefox it flicker for first 8 times of change then no flicker, but, chrome keep flickering each time – markpmark Mar 18 '20 at 21:26
  • 1
    I was having the same problem with Chrome. Images were flickering because I had the developer panel open. Nothing worked. But as soon as I closed the developer panel, F12, images stopped flickering. – hellork Apr 25 '20 at 07:40