Javascript/jQuery Image load when section on view | Speed Optimization

PHOTO EMBED

Thu Aug 18 2022 13:53:50 GMT+0000 (Coordinated Universal Time)

Saved by @mickeldav #javascript #jquery #speedoptimization

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');
});
content_copyCOPY