【问题标题】:Is it possible to make loading = 'lazy' work in <img /> with X axis?是否可以使用 X 轴在 <img /> 中使 loading = 'lazy' 工作?
【发布时间】:2020-12-17 11:01:57
【问题描述】:

我将img lazy loading 功能用于带有 X 轴滚动的页面。但它工作不正确,图像仅在页面上出现时才开始加载,而不是更早地加载。

例子:

function l(num) {
  document.getElementById('log').innerText += "loaded #" + num + " image\n";
}
.images {
  display: inline-block;
  width: 300px;
  overflow: hidden;
  overflow-x: visible;
  border: 1px solid magenta;
  white-space: nowrap;
}
#log {
  display: inline-block;
  vertical-align: top;
}
<div class="images">
  <img loading="lazy" src="https://picsum.photos/300/150?1" height="150" width="300" onload="l(1)" />
  <img loading="lazy" src="https://picsum.photos/300/150?2" height="150" width="300" onload="l(2)" />
  <img loading="lazy" src="https://picsum.photos/300/150?3" height="150" width="300" onload="l(3)" />
  <img loading="lazy" src="https://picsum.photos/300/150?4" height="150" width="300" onload="l(4)" />
  <img loading="lazy" src="https://picsum.photos/300/150?5" height="150" width="300" onload="l(5)" />
  <img loading="lazy" src="https://picsum.photos/300/150?6" height="150" width="300" onload="l(6)" />
  <img loading="lazy" src="https://picsum.photos/300/150?7" height="150" width="300" onload="l(7)" />
</div>
<div id="log" />

我得出的结论是,这只适用于 Y 轴上当前点下方的图像。

Y 轴是如何做到的?

更新日期:04.03.2021

懒惰地使用 X 轴。但懒惰的工作只在主要的“身体”滚动!当我使用overflow: auto 制作任何div 时,延迟加载根本不起作用!

【问题讨论】:

标签: javascript html css google-chrome


【解决方案1】:

你可以像这样使用 IntersectionObserver

const lazyInit = (element, fn) => {
    const config = {
      rootMargin: '0px 0px 50px 0px',
      threshold: 0
    };
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          observer.disconnect(); //drop observer and run the function {fn}
          fn();
        }
      });
      
    }, config);
    observer.observe(element);
  };
  document.querySelectorAll("img[data-src]").forEach(img => {
    lazyInit(img, function() {
      preloadImage(img);
    });
  });
  function preloadImage(img) {
    const src = img.getAttribute('data-src');
    if (!src) { return; }
    img.src = src;
  }

那你必须把img的src属性换成data-src

img 元素应该是这样的

<img data-src="https://picsum.photos/300/150?1" height="150" width="300" />

这里重要的是属性rootMargin。阅读更多here

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2020-01-18
    • 2021-09-03
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多