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
You can connect with me on Twitter or Linkedin.
Latest on My Blog
PHP Beginner's Tutorial
Beginner's PHP Tutorial
Image for Laravel High CPU Usage Because of File-based Session Storage
Laravel High CPU Usage Because of File-based Session Storage
Image for Resizing Droplets: A Personal Experience
Resizing Droplets: A Personal Experience
Image for Moving our CDN (10+ GB images) to a new server
Moving our CDN (10+ GB images) to a new server
Image for Disqus, the dark commenting system
Disqus, the dark commenting system
Image for Creating a Real-Time Chat App with PHP and Node.js
Creating a Real-Time Chat App with PHP and Node.js
Related Articles
20