javascript 使用lazysizes延迟加载背景图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47184717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:14:38  来源:igfitidea点击:

Lazyload background-image with lazysizes

javascriptjqueryjquery-lazyload

提问by Daiaiai

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:

我想用图书馆http://afarkas.github.io/lazysizes/加载背景图像“懒惰”
他们确实提到可以懒惰地加载“任何东西”。但是关于那个的整个文档是这样的:

<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?

我不明白如何将其用于背景图像。有没有人有这方面的经验?

回答by Panos Spiliotis

To load a background image using lazysizes use the data-bgattribute

要使用延迟大小加载背景图像,请使用该data-bg属性

example:

例子:

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

回答by Martino

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

如果要将图像加载为背景,请遵循此文档。这是lazysizes的插件

回答by Amit Dwivedi

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

如果你想使用lazyload加载背景图片,你只需要添加一小段代码(无需添加任何插件) -

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

回答by CyberMessiah

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

可能有人会发现这很有用。在我的情况下,使用相同的库 - “lazysizes”我不得不将data-bg更改为data-bgset

<div class="lazyload" data-bgset=""></div>

回答by Martino

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:

所需的lazysizes插件:

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