JSFiddle - React, Tailwind, and code Playground

by polaszk

HTML

<div id="container">
  <img src="http://thinkfuture.com/wp-content/uploads/2013/10/loading_spinner.gif" data-src="http://www.dogbazar.org/wp-content/uploads/2014/09/british-bull-dog-puppies.jpg">
  <img src="http://thinkfuture.com/wp-content/uploads/2013/10/loading_spinner.gif" data-src="https://images.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg">
  <img src="http://thinkfuture.com/wp-content/uploads/2013/10/loading_spinner.gif" data-src="http://www.dogbazar.org/wp-content/uploads/2014/09/british-bull-dog-puppies.jpg">
  <img src="http://thinkfuture.com/wp-content/uploads/2013/10/loading_spinner.gif" data-src="https://images.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg">
  <img src="http://thinkfuture.com/wp-content/uploads/2013/10/loading_spinner.gif" data-src="http://www.dogbazar.org/wp-content/uploads/2014/09/british-bull-dog-puppies.jpg">
  <img src="http://thinkfuture.com/wp-content/uploads/2013/10/loading_spinner.gif" data-src="https://images.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg">
  <img src="http://thinkfuture.com/wp-content/uploads/2013/10/loading_spinner.gif" data-src="http://www.dogbazar.org/wp-content/uploads/2014/09/british-bull-dog-puppies.jpg">
  <img src="http://thinkfuture.com/wp-content/uploads/2013/10/loading_spinner.gif" data-src="https://images.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg">
  <img src="http://thinkfuture.com/wp-content/uploads/2013/10/loading_spinner.gif" data-src="http://www.dogbazar.org/wp-content/uploads/2014/09/british-bull-dog-puppies.jpg">
  <img src="http://thinkfuture.com/wp-content/uploads/2013/10/loading_spinner.gif" data-src="https://images.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg">
  <img src="http://thinkfuture.com/wp-content/uploads/2013/10/loading_spinner.gif" data-src="http://www.dogbazar.org/wp-content/uploads/2014/09/british-bull-dog-puppies.jpg">
  <img...

CSS

img {
  display: block;
  height: 300px;
  width: auto;
}

JavaScript

function lazyLoad() {
  var allImages = $('#container').find('img');
  var bottomOfScreen = $(window).scrollTop() + window.innerHeight;
  var topOfScreen = $(window).scrollTop();

  $.each(allImages, function (index, value) {
    var topOfElement = $(value).offset().top;
    var bottomOfElement = $(value).offset().top + $(value).outerHeight();

    if((bottomOfElement > topOfElement) && (topOfScreen < bottomOfScreen)){
      $(value).attr('src', $(value).data('src'));
    }
  });
}

lazyLoad();

$(window).on('scroll', function() {
  lazyLoad();
});