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
Liked the article? Follow me on Twitter, or help Hyvor grow by funding Hyvor Talk.
Latest on Hyvor Developer
PHP Beginner's Tutorial
Beginner's PHP Tutorial
Image for Creating a Real-Time Chat App with PHP and Node.js
Creating a Real-Time Chat App with PHP and Node.js
Image for All About MYSQLI Prepared Statements in PHP
All About MYSQLI Prepared Statements in PHP
Image for Image Upload with AJAX, PHP, and MYSQL - The Beginner's Guide
Image Upload with AJAX, PHP, and MYSQL - The Beginner's Guide
Image for PHP Contact Form - The Email Method
PHP Contact Form - The Email Method
Image for The Best Way to Perform MYSQLI Prepared Statements in PHP
The Best Way to Perform MYSQLI Prepared Statements in PHP
0