Reputation: 1089
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
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
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
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
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
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