Nghiên cứu plugin lazy-elementor-background-images

https://gist.github.com/jrevillini/e2fe088455e4007e43a23b3364720690

Xemt thêm How To Maximize Website Speed By Lazy Loading Backgrounds

We all know faster websites are much better for user experience, improve conversion rates, and come pre-packed with bragging rights about GT Metrix scores.

But lately, the buzz around Google’s integration of Core Web Vitals into their search engine ranking algorithm in May of this year (2021) has everyone panicking over how to make their websites as fast as possible.

Truth be told, Core Web Vitals are less about how long it takes for a page to fully load (page load time), and more about the user perception of the loading experience:Speed Index measures how quickly content is visually displayed during page load.Speed Index - Web.dev

So, let’s just highlight the most common speed optimization strategies that you should look into implementing:

  • Get premium website hosting

  • Implement server-side and browser caching, including GZIP compression

  • Utilize less code and resources

  • Only load what’s necessary

  • Optimize, properly size, and compress images

  • Utilize the best image format for every image asset

  • Lazy load images

  • Defer loading of javascript

  • Defer loading of CSS

  • Preload fonts and use display “swap”

Now, you might have noticed the “Lazy load images” item in the list above and thought, “wouldn’t that include background images?”.

Unfortunately, most plugins that lazy load images will not lazy load backgrounds. Some plugins will lazy load backgrounds but only if the background images are defined inline in the HTML, like so:

  
    <div id=”hero” style=”background-image: url(‘\my-background.jpg’)”> </div>
  

Unless you’re hand-coding the section or website, applying that inline code is either not easy, or not possible.

If you’re using Elementor, Beaver Builder, or even Oxygen - getting background images to lazy load is usually something people throw in the towel for.

So does that mean we’re out of luck? Heck no … here’s where this article get’s good! we’re going to show you how you can easily add background image lazy loading to any website regardless of which builder you're using.

Lazy Loading

First let’s just quickly go over what lazy-loading is, because this will help you to understand how the code we’ll share here works and how to easily implement it.

Lazy loading is the process of only loading something when it’s required. In the case of images, this means the images are only loaded when the image elements come into view.

Part One - The Script

The basic gist of this code is this:

  • All elements with the class .lazy-bg are stored in an array

  • An IntersectionObserver is used to detect when any of those elements in that array come into view

  • When the element enters the viewport a class of .bg-visible is added to the element

If you’re website is built on top of WordPress, you can simply save the script and enqueue it in your functions.php file like so:

  
    wp_enqueue_script( 'bg-lazy-loading', '/path-to-js/bg-lazy-loading.js’, array( 'jquery' ), ‘1.0.0’, true );
  
document.addEventListener("DOMContentLoaded", function() {
  var lazyBackgrounds = [].slice.call(document.querySelectorAll(".lazy-bg"));

  if ("IntersectionObserver" in window && "IntersectionObserverEntry" in window && "intersectionRatio" in window.IntersectionObserverEntry.prototype) {
    let lazyBackgroundObserver = new IntersectionObserver(function(entries, observer) {
      entries.forEach(function(entry) {
        if (entry.isIntersecting) {
          entry.target.classList.add("bg-visible");
          lazyBackgroundObserver.unobserve(entry.target);
        }
      });
    });

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

Part Two - Implementation

One you’ve got the script running, we can now start setting up our elements with background images. I would advise that you don’t do any of this until the page is fully built. This should be the last step you take before taking the page or site live.

Step 1 - Add the Lazy Loading Class

Step 2 - Set the Background Image Using the BG-Visible Class

With either Oxygen or Elementor, you have several ways you can add the CSS. It doesn’t really matter how or where you add it - what matters is that you have the CSS somewhere. In the examples above, we added the CSS in Elementor’s Custom CSS for the specific element. In the Oxygen example, we added a Code Block and put the CSS in there.

Conclusion

So that’s all there is to it! With a few minutes of work, you’d have reduced your page “weight”, or size, quite a bit. Most background images are in the 80KB - 180KB range, with some being larger in size depending on the amount of detail and the quality of the image.

Consider a page with 3 background images, that’s a savings of between 210KB - 540KB in page size. That’s a half a megabyte!

This is one little secret that can shave off a solid amount of time off your page load times, and help you get one step closer to optimizing the following Core Web Vitals:

  • First Contentful Paint

  • Largest Contentful Paint

  • Speed Index

  • Time to Interactive

Last updated