Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 871
Daiaiai Avatar asked Nov 08 '17 16:11

Daiaiai


4 Answers

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>
like image 198
Panos Spiliotis Avatar answered Oct 30 '22 12:10

Panos Spiliotis


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 + ')';
    }
});
like image 42
Amit Dwivedi Avatar answered Oct 30 '22 10:10

Amit Dwivedi


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

like image 31
Martino Avatar answered Oct 30 '22 12:10

Martino


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>
like image 33
CyberMessiah Avatar answered Oct 30 '22 11:10

CyberMessiah