PageSpeed: Background image lazyload

PageSpeed: Background image lazyload

Hi my lazy (loading) readers :)

This is first of my short blog posts about increasing your page speed with some simple steps.

Today we will talk about lazyloading background images. I think everybody know how lazyloading works, if not leave me a commect and I will create a post about that too.

Lazyloading of background images is more tricky, because it is not supported in default by browsers. But there is a solution with some CSS and JavaScript

CSS

CSS is quite straightforward. We want to disable the background-image until it's visible for user. I am adding :before and :after too, because sometimes they are used to display images.

Add this class to all elements that contain a background image and you want to apply lazyload to it.

I wouldn't recommend putting lazyload on the header images. You want them to be loaded immediately.

.lazyload-bg,
.lazyload-bg::before,
.lazyload-bg::after {
  background-image: none !important;
}

JavaScript

JavaScript looks magical but don't worry it's easy. It checks all elements with our lazyload-bg class and then removes this class if the element is visible to user. When this class is removed real background-image is loaded.

document.addEventListener('DOMContentLoaded', function() {
   var lazyBackgrounds = [].slice.call(document.querySelectorAll('.lazyload-bg'));

   if ('IntersectionObserver' in window) {
      let lazyBackgroundObserver = new IntersectionObserver(function(entries, observer) {
         entries.forEach(function(entry) {
            if (entry.isIntersecting) {
               entry.target.classList.remove('lazyload-bg');
               lazyBackgroundObserver.unobserve(entry.target);
            }
         });
      });

      lazyBackgrounds.forEach(function(lazyBackground) {
         lazyBackgroundObserver.observe(lazyBackground);
      });
   }
});

Example

Of course I need to provide an example :) We can use these nice tigers. If you start scrolling in the result window, you will see that the images are loaded one by one.

It's more obvious if you have slow internet like me.

And how do I know it's working?

You need to open Inspect window in your browser and go to tab Network. Here you can see, that on page load there is only 1 tiger image loaded.

image.png

But when you start scrolling, page loads more images.

image.png

And in the final it loads all 7 of them.

image.png

If you've read this far, thank you very much. This is my first post and I know I still have a lot to learn. Both about writing and English :D If you have any questions or comments, please let me know.

Did you find this article valuable?

Support Zbynek Nedoma by becoming a sponsor. Any amount is appreciated!