Lazy Loading Images for Flexslider

Flexslider is one of the most used sliders, for good reason. This snippet helps lazy load your images.

In order to create a perceived performance for users, we as authors shouldn’t allow the loading of every single image at once for sliders or carousels. In this snippet we only load the first and second image on init window load.

This perceived performance is a bit faster when we advance slides (the current slide also loads the next slide as you traverse). Make sure you don’t lazy load the first image of your slider.


<html>
<body>
<!-- Slider Markup -->
<section class="slider">
  <div class="flexslider">
    <ul class="slides">
      <li>
        <img src="your_image_link.jpg" alt="">
      </li>
      <li>
        <img class="lazy" data-src="your_image_link.jpg" alt="">
      </li>
      <li>
        <img class="lazy" data-src="your_image_link.jpg" alt="">
      </li>
      <li>
        <img class="lazy" data-src="your_image_link.jpg" alt="">
      </li>
      <li>
        <img class="lazy" data-src="your_image_link.jpg" alt="">
      </li>
    </ul>
  </div>
</section>

<!-- Scripts inserted before closing body tag of markup -->
<script src="jquery.flexslider.min.js"></script>
<script>
$(window).load(function() {
  $('.flexslider').flexslider({
touch: true,
slideshow: false,
controlNav: true,
slideshowSpeed: 7000,
animationSpeed: 600,
initDelay: 0,
start: function(slider) { // Fires when the slider loads the first slide
var slide_count = slider.count - 1;

      $(slider)
        .find('img.lazy:eq(0)')
        .each(function() {
          var src = $(this).attr('data-src');
          $(this).attr('src', src).removeAttr('data-src');
        });
    },
    before: function(slider) { // Fires asynchronously with each slider animation
      var slides     = slider.slides,
          index      = slider.animatingTo,
          $slide     = $(slides[index]),
          $img       = $slide.find('img[data-src]'),
          current    = index,
          nxt_slide  = current + 1,
          prev_slide = current - 1;

      $slide
        .parent()
        .find('img.lazy:eq(' + current + '), img.lazy:eq(' + prev_slide + '), img.lazy:eq(' + nxt_slide + ')')
        .each(function() {
          var src = $(this).attr('data-src');
          $(this).attr('src', src).removeAttr('data-src');
        });
    }

});
});
</script>
</body>
</html>

Flexslider Properties Documentation : https://github.com/woothemes/FlexSlider/wiki/FlexSlider-Properties