Brownrice Brownrice - 6 months ago 18
jQuery Question

Flexslider lazyloading - only load an image when it's truly needed

This is really only following on from an answer to Flexslider lazyloading here I am using that code which I Have pasted below. I would like to alter it so that images only loaded when truly needed.

I tried the other Flexslider properties, before: and after: but they created a delay on the first slide? Please can I get some help with this.

$('#slider').flexslider({
start: function (slider) {
// lazy load
$(slider).find("img.lazy").each(function () {
var src = $(this).attr("data-src");
$(this).attr("src", src).removeAttr("data-src");
});
}
});

Answer

I got some help in the end, here we have less code :)

Jquery:

$(window).load(function() {
 $('#sld-auto-930').flexslider({
  // put your settings properties here
  after: function (slider) {       
  //instead of going over every single slide, we will just load the next immediate slide
  var slides = slider.slides,
      index = slider.animatingTo,
      $slide = $(slides[index]),
      $img = $slide.find('img[data-src]');
      if($img){
      $img.attr("src", $img.attr('data-src')).removeAttr("data-src");
     }
}
});

HTML:

if($i > 0) {
    echo '<img class="lazy'.$i.'"src="" data-src="'.$src.'" alt="'.$alt.'">';
 }else {
    echo '<img class="first'.$i.'"src="'.$src.'"  alt="'.$alt.'">';                         }       
$i++;