Lazy Loading Images

Lazy loading improves your site's speed as it allows you to load the images only if the user scrolled to the image's view.

This is a simple function to implement Lazy loading in your website. (Supports IE 9+) To use it, you will need to add image's URL into data-src attribute. The image should have the class lazy to be loaded lazily.


!(function() {
    function inViewport(el) {
        var rect = el.getBoundingClientRect();
        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.top <= (window.innerHeight || document.documentElement.clientHeight)
        )
    }
    var images = [].slice.call(document.querySelectorAll("img.lazy"));
    function handleScroll() {
        for (var i = 0, len = images.length; i < len; i++) {
            if (inViewport(images[i]))
                loadImage(i);
        }
    }
    function loadImage(i) {
        var el = images[i],
            src = el.getAttribute("data-src");
    
        if (!src)
            return;
        var image = new Image();
        image.src = src;
        image.onload = function() {
            if (!! el.parent)
                el.parent.replaceChild(img, el)
            else
                el.src = src;
        }
        images.splice(i, 1);
    }
    handleScroll();
    window.addEventListener("scroll", handleScroll);
})();

Copy & paste this code at the bottom of your webpage. If you need a minified version here it is.

Tagged: HTML Javascript
Written By
Supun Kavinda
Written On
Apr 17, 2019
Last Updated On
Apr 17, 2019
Latest on Hyvor Developer
Creating a Real-Time Chat App with PHP and Node.js
All About MYSQLI Prepared Statements in PHP
Image Upload with AJAX, PHP, and MYSQL - The Beginner's Guide
PHP Contact Form - The Email Method
0