Lazy Loading Fade Effect

Chapter 7 3 mins

Learning outcomes:

  1. Giving a fade effect to the loader

Introduction

A lazy loader doesn't feel elegant at all unless it is given some sub features like a loading icon. This notion was dealt with in the previous Loading Icons chapter where we gave different types of icons to our .lazy container uptil the the point the underlying image loaded.

But is an icon the only thing that can make our loader look nice? Is there anything else we can do in addition? That anything is to give a fade-in effect to our image as it loads into view.

Building the fade effect

The idea is that instead of showing the image instantly as it loads we transitionally fade it in. Giving a fade-in effect in CSS is extremely simple — just the matter of three properties: opacity, visibility and transition.

We'll start by constructing a class .lazy_img--loading to be given to the lazy image .lazy_img.

Note that we're following the BEM naming convention in the class name lazy_img--loading. As the name might imply, the class lazy_img--loading implies that the underlying lazy image is currently loading.

This class serves to hold the initial state of our transition i.e an opacity of 0 and a hidden visibility.

Consider the following CSS:

.lazy_img--unloaded {
    opacity: 0;
    visibility: hidden;
}

Now let's give .lazy_img a transition property to smoothly transition between its initial and final states.

.lazy_img {
    -webkit-transition: 0.5s linear;
    transition: 0.5s linear;
}
If you've worked with CSS and JavaScript class toggles and then transitions, you'll agree that there isn't anything complicated or new in this.

For the JavaScript, we just need to add the class .lazy_img--loading to the lazy image the moment it's fetched into lazyImage; and then remove it, once it successfully gets loaded.

Below shown is the first part of adding the class:

var lazyImage = document.getElementsByClassName("lazy_img")[0];
var offset = lazyImage.getBoundingClientRect().top + window.pageYOffset - window.innerHeight;

lazyImage.classList.add("lazy_img--loading"); // add the class

And following is the second part of removing the class once the image gets loaded:

function loadImage(img) {
    img.onload = function() {
        icon.style.display = "none"; // hide the icon
        this.classList.remove("lazy_img--unloaded"); // show the image
    }

    img.src = img.getAttribute("data-src");
}
We can also add the class lazy_img--loading to the lazy image manually in the HTML, but it's more convenient to add it automatically via JavaScript.
Depending on the way you gave a loading icon to your lazy loader, you might need to include icon.style.display = "none" in the load event of lazyImage as illustrated above in line 3. Without it the icon will not disappear, and remain animating.

This marks the completion of the fade effect. Check it out below and witness the pure elegance of our lazy loader!

Fade Effect Loader