Preloaded images flash at different rates

3039 views javascript
4

I'm calling images from a folder at random and putting them in HTML img tags using PHPs glob function.

I'm then using JS to read the URLs and flip the CSS background image of div#wrapper, 300ms for each image. The images should be preloaded as they have HTML img tags. They are being hidden from the user using the following CSS (which should not stop preloading as "display: none" does):

.visuallyhidden { 
    position: absolute; 
    overflow: hidden; 
    clip: rect(0 0 0 0); 
    height: 1px; width: 1px; 
    margin: -1px; padding: 0; border: 0; 
}

Nonetheless I'm experiencing the images flashing inconsistently / at different rates. It seems that larger file size images cause this to happen, but the images should be preloaded so I'm not sure why this is occurring.

My JS looks like this:

var slides = [];

$('.slide').each(function(index){
    slides.push($(this).attr('id'));
});

var slide = 0;

function changeImage(){
  if (slide < 10){
    var currentSlide = $("#" + slides[slide]);
      $('#wrapper').css('background-image', '');
        $('#wrapper').css('background-image', 'url("' + currentSlide.attr('src') + '")');
    slide++
    } else {
        $('#headline').removeClass('visuallyhidden');
        $('#wrapper').css('background-image', '');
        $('#wrapper').css('background-color', '#ef3308');
    }
}

setInterval(changeImage, 300);

The site is http://robertirish.com.

Is there a better way to do this / can anyone explain why it's happening?

answered question

1 Answer

12

I'm going to guess it's a loading issue: either that CSS is interfering with preload or else it's being treated differently because you're loading it into the background of another element rather than using the img that you preloaded. Instead, I would load all the images inside the div, absolute-positioned on top of each other, and then just remove them one by one:

CSS:

#wrapper{
  position: relative;
}

#wrapper img{
  position: absolute;
  top: 0px;
  bottom: 0px;
  left: 0px;
  right: 0px;
}

HTML:

<div id="wrapper">
  <img src="image1.png">
  <img src="image2.png">
  <!--etc-->
</div>

JS:

$(document).on('ready', function(){
  var images = [];
  $("img", "#wrapper").each(function(){
    images.push(this);
  });

  var timer = setInterval(moveNextImg, 300);

  function moveNextImg(){
    if (images.length)
      $(images.pop()).remove();
    else
      clearTimeout(timer);
  }
});

posted this

Have an answer?

JD

Please login first before posting an answer.