Snippets Collections
function getMeta(url, callback) {
    var img = new Image();
    img.src = url;
    img.onload = function() { callback(this.width, this.height); }
}
getMeta(
  "http://snook.ca/files/mootools_83_snookca.png",
  function(width, height) { alert(width + 'px ' + height + 'px') }
);
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');
});
star

Thu Aug 18 2022 14:08:22 GMT+0000 (Coordinated Universal Time)

#javascript #jquery #speedoptimization

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension