i'm trying to improve my page speed, in order to do that i have used many lazy loading plugin, they work for normal images but not for background images. i need to lazy load background images to improve my page speed please help!!!

1 Answer 1


That is nothing that can be installed by a plugin or, at least, would be necessary for you to work on it.

However, you can build this yourself.

Step 1: Enqueue the IntersectionObserver polyfill you can find here: https://github.com/w3c/IntersectionObserver/blob/master/polyfill/intersection-observer.js to get Support for older Browsers.

Step 2: Change the code of your HTML-Elements which use a Background Image. Add a class (let's say lazybg) and put the background-image into a data-attribute (let's say data-lazybg). So you change this:

<div class="mybackgroundimagediv" style="background-image:url(img/myawesomeimage.jpg);"></div>

into this:

<div class="mybackgroundimagediv lazybg" data-lazybg="http://myawesomewebsite.com/img/myawesomeimage.jpg" style=""></div>

Step 3: Write some javascript to load the background-image lazily:

let lazyObjectObserver = new IntersectionObserver(function(entries, observer) {
        entries.forEach(function(entry) {
            if (entry.isIntersecting) {
                let lazyObject = entry.target;
                if(!(lazyObject.dataset.lazybg == '')){
                    bgsrc = lazyObject.dataset.lazybg;
                    lazyObject.style.backgroundImage = 'url('+bgsrc+')';
                    lazyObject.dataset.lazybg = '';
    },{ rootMargin: "0px 0px 0px 0px" });

document.addEventListener("DOMContentLoaded", function() {
  var lazyObjects = [].slice.call(document.querySelectorAll(".lazybg"));
  lazyObjects.forEach(function(lazyObject) {

Success! Your prepared divs will now load the background-image when they come into the viewport!

Not the answer you're looking for? Browse other questions tagged or ask your own question.