加载图像与页面加载分开

Load images separated from page loading

我目前使用的是延迟加载图片,即在页面加载时加载所有图片,并在加载图片后显示。在这种方法中,页面显示在浏览器的选项卡部分加载,直到所有图像都下载完毕。

现在,我想加载与页面加载分开的图像。与google图片一样,页面加载在1秒内,图片是一张一张加载的,浏览器标签页不显示页面加载。

我怎样才能做到这一点?

所以,最后一个问题:如何首先完全加载页面,而不从服务器下载图像,然后在滚动条到达那里时下载图像。到那时,图像可能是一个灰色框。

正在加载图像。

加载属性

我们可以使用 loading attribute 的本机延迟加载。

这是 demo.

<div><img src="https://placeimg.com/410/410/any" loading="lazy" width="410" height="410"></div>

目前,最新版本 Chrome、Firefox 和 Edge support 本机延迟加载。

请注意,浏览器中的距离阈值确实有所不同。

Chrome

The distance threshold after which the deferred content will start loading-in depends on factors including the current effective connection type, and whether Lite mode is enabled. The distance is chosen so that the deferred content almost always finishes loading by the time it becomes visible.

Firefox

Tells the user agent to hold off on loading the image until the browser estimates that it will be needed imminently. For instance, if the user is scrolling through the document, a value of lazy will cause the image to only be loaded shortly before it will appear in the window's visual viewport.

路口观察器

我们还可以跨浏览器使用 IntersectionObserver API to determine when your images are in view. This offers better compatibility 并更好地控制图像加载的时间和方式。

CodePen

HTML

<div>
    <img src="data:," 
        data-src="https://placeimg.com/410/410/any" 
        class="lazy" 
        alt="" 
        width="410" 
        height="410" />
</div>

JS

document.addEventListener("DOMContentLoaded", lazyLoad);

function lazyLoad() {
  const images = [].slice.call(document.querySelectorAll("img.lazy"));
  var config = {
    // If the image gets within 500px in the Y axis, start the download.
    rootMargin: "500px 0px",
    // detect when visibility passes the 1% mark
    threshold: 0.01
  };

  if ("IntersectionObserver" in window) {
    const observer = new IntersectionObserver(showImage, config);

    images.forEach(function (image) {
      observer.observe(image);
    });
  }
}

function showImage(entries, observer) {
  entries.forEach(function (entry) {
    if (entry.isIntersecting) {
      const image = entry.target;
      image.src = image.dataset.src;

      observer.unobserve(image);
    }
  });
}

现有图书馆

还有现有的 JavaScript 个库,例如 lazySizes