How to Lazy Load div background images

I've found this on the plugin's official site:

<div class="lazy" data-original="img/bmw_m1_hood.jpg" style="background-image: url('img/grey.gif'); width: 765px; height: 574px;"></div>

$("div.lazy").lazyload({
      effect : "fadeIn"
});

Source: http://www.appelsiini.net/projects/lazyload/enabled_background.html


Mid last year 2020 web.dev posted an article that shared some new ways to do this with the the new IntersectionObserver which at the time of writing this answer is supported in all major browsers. This will allow you to use a very light weight background image, or background color placeholder while you wait for the image to come to the edge of the viewport and then it is loaded.

CSS

.lazy-background {
  background-image: url("hero-placeholder.jpg"); /* Placeholder image */
}

.lazy-background.visible {
  background-image: url("hero.jpg"); /* The final image */
}

Javascript

document.addEventListener("DOMContentLoaded", function() {
  var lazyBackgrounds = [].slice.call(document.querySelectorAll(".lazy-background"));

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

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

First you need to think off when you want to swap. For example you could switch everytime when its a div tag thats loaded. In my example i just used a extra data field "background" and whenever its set the image is applied as a background image.

Then you just have to load the Data with the created image tag. And not overwrite the img tag instead apply a css background image.

Here is a example of the code change:

if (settings.appear) {
    var elements_left = elements.length;
    settings.appear.call(self, elements_left, settings);
}
var loadImgUri;
if($self.data("background"))
    loadImgUri = $self.data("background");
else
    loadImgUri  = $self.data(settings.data_attribute);

$("<img />")
    .bind("load", function() {
        $self
            .hide();
        if($self.data("background")){
            $self.css('backgroundImage', 'url('+$self.data("background")+')');
        }else
            $self.attr("src", $self.data(settings.data_attribute))

        $self[settings.effect](settings.effect_speed);

        self.loaded = true;

        /* Remove image from array so it is not looped next time. */
        var temp = $.grep(elements, function(element) {
            return !element.loaded;
        });
        elements = $(temp);

        if (settings.load) {
            var elements_left = elements.length;
            settings.load.call(self, elements_left, settings);
        }
    })
    .attr("src", loadImgUri );
}

the loading stays the same

$("#divToLoad").lazyload();

and in this example you need to modify the html code like this:

<div data-background="http://apod.nasa.gov/apod/image/9712/orionfull_jcc_big.jpg" id="divToLoad" />​

but it would also work if you change the switch to div tags and then you you could work with the "data-original" attribute.

Here's an fiddle example: http://jsfiddle.net/dtm3k/1/


EDIT: the post from below is from 2012 and absolete by now!

I do it like this:

<div class="lazyload" style="width: 1000px; height: 600px" data-src="%s">
    <img class="spinner" src="spinner.gif"/>
</div>

and load with

$(window).load(function(){

    $('.lazyload').each(function() {

        var lazy = $(this);
        var src = lazy.attr('data-src');

        $('<img>').attr('src', src).load(function(){
            lazy.find('img.spinner').remove();
            lazy.css('background-image', 'url("'+src+'")');
        });
    
    });

});