require(['jquery'], function ($) { const offset = 200; let images; $.fn.processScroll = function() { for (let i = 0; i < images.length; i++) { let img = images[i]; if (elementInViewport(img)) { loadImage(img, function () { images.splice(i, 1); i--; }) } } }; function loadImage($el, $fn) { jQuery($el).attr('src', jQuery($el).attr('data-src')); $fn ? $fn() : null; } function elementInViewport($el) { if ($el === undefined) return false; let $rect = $el.getBoundingClientRect(); return ($rect.top > 0 && $rect.left > 0 && $rect.top <= (window.innerHeight || document.documentElement.clientHeight) + offset ); } !function(window) { jQuery(document).ready(function() { images = new Array(); let query = jQuery('img.lazy'); jQuery().processScroll(); query.each(function() { images.push(this); }); jQuery().processScroll(); jQuery(window).bind('scroll', jQuery().processScroll); }); }(this); });