9

I want to load a background-image "lazy" with the library http://afarkas.github.io/lazysizes/
They do mention that the loading of "anything" lazily is possible. But the whole documentation on that is that one:

<div data-ride="carousel" data-script="assets/js/bootstrap.min.js" class="carousel lazyload">
    <!-- widget content -->
<div>

And I don't get how I could use that for a background-image. Does anybody have experience there on that?

Daiaiai
  • 1,019
  • 3
  • 12
  • 28

6 Answers6

15

To load a background image using lazysizes use the data-bg attribute

import "lazysizes/plugins/unveilhooks/ls.unveilhooks";

Usage example:

<div class="lazyload" data-bg="/path/to/image.jpg"></div>
Mahsa2
  • 412
  • 6
  • 15
Panos Spiliotis
  • 801
  • 1
  • 9
  • 18
  • 6
    You'll need the unveilhooks plugin for this to work: https://github.com/aFarkas/lazysizes/tree/e305d28d4b6c4ff9f12dd4d438d5d7c5d41574db/plugins/unveilhooks – martinedwards May 09 '19 at 12:45
  • 1
    Is it possible to lazyload a webp and a jpeg as a fallback for using as background-image of a div? – lordparthurnaax May 05 '20 at 19:36
12

If you want to load background image using lazyload just you need to add one small block of code (No need to add any plugin) -

//add simple support for background images:
document.addEventListener('lazybeforeunveil', function(e){
    var bg = e.target.getAttribute('data-bg');
    if(bg){
        e.target.style.backgroundImage = 'url(' + bg + ')';
    }
});
Amit Dwivedi
  • 157
  • 1
  • 5
3

If you want to load an image as background, follow this doc. This is a plugin of lazysizes

Martino
  • 186
  • 13
2

Probably someone may find this useful. In my case, using the same library - "lazysizes" I had to change data-bg for data-bgset:

<div class="lazyload" data-bgset=""></div>
CyberMessiah
  • 1,084
  • 11
  • 14
1

As mention before you need to add some plugin to do that. This is the configuration that i use to all my project.

Required lazysizes plugin:

than you can set your custom breakpoint in this way

window.lazySizesConfig = window.lazySizesConfig || {};
window.lazySizesConfig.customMedia = {
    '--small'   : '(max-width: 576px)',
    '--medium'  : '(max-width: 768px)'
};

And here the markup

<div class="lazyload" data-bgset="URL-OF-SMALL-IMAGE[--small] URL-OF-MEDIUM-IMAGE[--medium] | URL-OF-FULL-SIZE-IMAGE", data-sizes="auto")
Martino
  • 186
  • 13
0

Verify the version of the Lazyload.

The version to work this:

<div class="lazy" data-bg="/path/to/image.jpg"></div>

is:

<script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload@17.6.1/dist/lazyload.min.js"></script>

ps: do not forget insert the call

var lazyLoadInstance = new LazyLoad({
  elements_selector: ".lazy",
  load_delay: 100,
  effect : "fadeIn"
  // ... more custom settings?
  });
Leffa
  • 369
  • 4
  • 7