Fade In Effect for your LazyLoaded images

WP Rocket gives you the smart feature of LazyLoad for your images and iframes (including video). Those resources are loaded only when they have to be displayed on the screen of your visitor, which makes your site load much faster. Even though the image is not immediately displayed, LazyLoad also provide an alternative tag for SEO (described below).

The Principle

The LazyLoad script uses the data-lazy-src attribute to store the URL of your image. It also puts an original image tag in a <noscript> tag for SEO and accessibility reasons. When your image has to appear (because the user has scrolled), the data-lazy-src attribute value comes to replace the value of the src attribute and makes the image appear suddenly.

A Simple CSS3 Solution

Thanks to the attribute selector (Internet Explorer 7 compatible), it is possible to target elements depending on attributes they own. When the data-lazy-src attribute passes its value to the src attribute of your image, the former disappears, leaving the complete src attribute.

In other words, it is possible to distinguish two states for our images:

  • here but not visible (the data-lazy-src attribute is set)
  • here and visible (the data-lazy-src attribute disappear and src attribute begins with “http”)

The following CSS code lets you make you the image fade in with a transition. Paste this code into your style.css (or another of your CSS theme files) :

/* Image with 'data' attribute is hidden */
img[data-lazy-src] {
/* we set the opacity to 0 */
   opacity: 0;
}
/* Image without 'data' attribute is (or becomes) visible */
img.lazyloaded {
/* prepare the future animation */
   -webkit-transition: opacity .5s linear 0.2s;
       -moz-transition: opacity .5s linear 0.2s;
                 transition: opacity .5s linear 0.2s;
/* we set the opacity to 1 to do the magic */
   opacity: 1;
}

If the user’s web browser doesn't support CSS3 transition properties, this code will do nothing.