jQuery图片懒加载和WebP格式,备用方案

3

我有些困惑如何在jquery lazyload中使用图片回退解决方案。我使用的是这个库:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>

目前我的图片是这样集成的:

<img class="center lazy" data-original="./bilder/uebersetzung-marketing-bwl.png" width="593>

但是,webp的回退方案结构如下:

<picture>
      <source class="center lazy" srcset="./bilder/Uebersetzungsdienst-Jena-BM-Translations.webp" type="image/webp">
      <img class="center lazy" src="./bilder/Uebersetzungsdienst-Jena-BM-Translations.png" width="1920" height="97" alt="Uebersetzungsdienst-Jena-BM-Translations">
</picture>

我的问题: 集成的lazyload查找data-original,因此无法使用srcset。是否有解决方案?

如果可能的话,我希望不使用另一个库,而是“简单地”添加一些代码。


你是指在源代码中添加imgWindowwidth refDesktop center吗? - mahan
我编辑了我的问题,希望现在更清楚了? - Krystian
1个回答

2
我找到了解决方案。需要以特定格式添加带有自定义属性的数据。 这段代码可以完美运行,并有助于页面优化,您可以添加Web或其他格式的图像。
注意:所有格式相同但名称不同的图像,例如:
- image_1.png - image_1.jpg - image_1.webp 只需更改扩展名即可。
<!-- Add this for show image  -->
<div class="lazy" data-name="image path1 without extension |image default extension (.png)|image alt tag|image classes"></div>
<div class="lazy" data-name="image path2 without extension |image default extension (.png)|image alt tag|image classes"></div>
<div class="lazy" data-name="image path3 without extension |image default extension (.png)|image alt tag|image classes"></div>

<!-- Add scripts in bottom  -->
<script>
function lazy_load(){
    $('.lazy').each(function(img){
        var scrollTop = window.pageYOffset;
        var this_offset=$(this).offset().top + $(this).outerHeight();
        var window_offset=$(window).scrollTop()+ $(window).height();
        if($(this).offset().top + $(this).outerHeight() <= ($(window).scrollTop()+ $(window).height())){
            var path_src=$(this).attr('data-name');
            var split_data=path_src.split('|');
            var img_html='<picture>'+
                '<source srcset="'+split_data[0]+'.webp" type="image/webp">'+
                '<source srcset="'+split_data[0]+split_data[1]+'" type="image/'+split_data[1].replace('.','')+'">'+
                '<img src="'+split_data[0]+split_data[1]+'" alt="'+split_data[2]+'" class="'+split_data[3]+'">'+
                '</picture>';
            $(this).html(img_html);
            $(this).show(1000);
            $(this).removeClass('lazy');
        }
    });
}
$(window).on('resize scroll', function(){
    lazy_load();
});
</script>

懒加载现在完美运行。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接