performance - jquery lazyload images 和 webp with fallback

标签 performance lazy-loading webp jquery-lazyload

我有点困惑如何结合 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。有解决方案吗?

如果可能的话,我宁愿不使用其他库,而是“简单地”添加一些代码。

最佳答案

我找到了解决方案。需要添加具有自定义属性的特定格式的数据。 此代码完美运行,有助于优化您添加网页或其他格式图像的页面。

注意:所有具有相同名称的格式图像,如,

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

延迟加载现在运行良好。

关于performance - jquery lazyload images 和 webp with fallback,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53671400/

相关文章:

Node.js - 将 webp 转换为 jpeg 作为缓冲区(在内存中)

java - 如何在android/java中将动画webp转换为gif?

php - 使用 imagewebp 将 jpg 转换为 webp

java - 获取动态生成的资源名称/字符串的 Drawable id

algorithm - 提高性能(超时错误)

sql - GETDATE() 和 DateTime.Now 一样昂贵吗?

bootstrap-4 - 如何延迟加载 Bootstrap 4 卡图像?

javascript - Knockout - 如何用新值重置动态可观察数组

java - 启动 100 个按钮的更有效方法

Angular 7 与 child 的 child 延迟加载