Daiaiai
Daiaiai

Reputation: 1089

Lazyload background-image with lazysizes

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?

Upvotes: 10

Views: 27317

Answers (6)

Leffa
Leffa

Reputation: 494

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/[email protected]/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?
  });

Upvotes: 0

Panos Spiliotis
Panos Spiliotis

Reputation: 819

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>

Upvotes: 16

CyberMessiah
CyberMessiah

Reputation: 1268

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>

Upvotes: 4

Amit Dwivedi
Amit Dwivedi

Reputation: 167

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 + ')';
    }
});

Upvotes: 13

Martino
Martino

Reputation: 206

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")

Upvotes: 1

Martino
Martino

Reputation: 206

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

Upvotes: 3

Related Questions