document.addEventListener("DOMContentLoaded", function() { $("img").each(function() { $(this).attr("data-src",$(this).attr("src")); $(this).attr("src",'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='); }); var $lazy_elements = $('img'); var $window = $(window); function check_if_in_view() { var window_height = $window.height(); var window_top_position = $window.scrollTop(); var window_bottom_position = (window_top_position + window_height); $.each($lazy_elements, function() { var $lazy_element = $(this); var lazy_element_height = $lazy_element.outerHeight(); var lazy_element_top_position = $lazy_element.offset().top; var lazy_element_bottom_position = (lazy_element_top_position + lazy_element_height); //check to see if this current container is within viewport if ((lazy_element_bottom_position >= window_top_position) && (lazy_element_top_position <= window_bottom_position)) { if($lazy_element.attr('data-src')) { $lazy_element.attr("src",$lazy_element.attr('data-src')); } } }); } $window.on('scroll resize', check_if_in_view); $window.trigger('scroll'); });
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter