使用 JavaScript 延迟加载图像是如何工作的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9667631/
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-26 07:23:34  来源:igfitidea点击:

How lazy loading images using JavaScript works?

javascriptimagescrolllazy-loading

提问by xiaohan2012

I am curious about how lazy loading images, images that will be loaded when scrolled to them, works.

我很好奇延迟加载图像(滚动到它们时将加载的图像)如何工作。

Any hint?

任何提示?

回答by JKirchartz

Here's a how-to, using plugins: http://www.webresourcesdepot.com/lazy-loading-of-images-resources-you-need/here's the jquery plugin: http://www.appelsiini.net/projects/lazyload

这是使用插件的操作方法:http: //www.webresourcesdepot.com/lazy-loading-of-images-resources-you-need/这是 jquery 插件:http: //www.appelsiini.net/projects/懒加载

basically you put a dummy image in your srcattribute and add another attribute for the actual image, JS detects the scroll position of the page, and loads the image data once you get close enough to the image. it does that by replacing the srcwith the source of the actual image.

基本上,您在src属性中放置一个虚拟图像并为实际图像添加另一个属性,JS 会检测页面的滚动位置,并在您离图像足够近时加载图像数据。它通过将 替换src为实际图像的来源来实现。

here's another explanation: http://engineering.slideshare.net/2011/03/faster-page-loads-with-image-lazy-loading/

这是另一种解释:http: //engineering.slideshare.net/2011/03/faster-page-loads-with-image-lazy-loading/

回答by anoraq

And example on how to do this, easily.

以及如何轻松做到这一点的示例。

<img src="/images/lazy.jpg" data-real-src="/images/company-1.jpg">

The "lazy.jpg" can be used on all images, which will result in really just one image is loaded (and it's a 1x1px small weight image). So, consider I'm having a list of 250 stores to visit, with a company logo for each. Could look like this:

"lazy.jpg" 可用于所有图像,这将导致实际上只加载一个图像(并且它是一个 1x1px 的小重量图像)。因此,请考虑我有一个要访问的 250 家商店的列表,每个商店都有一个公司徽标。看起来像这样:

<img src="/images/lazy.jpg" data-real-src="/images/company-1.jpg">
<img src="/images/lazy.jpg" data-real-src="/images/company-2.jpg">
<img src="/images/lazy.jpg" data-real-src="/images/company-3.jpg">
...

Then comes the magic! Put this in your javascript file:

然后是魔法!把它放在你的javascript文件中:

$('img[src="/images/lazy.jpg"]').each(function(index, el) {
    $(el).attr('src', $(el).data('real-src'));
});

And wacka-wacka, all the lazy.jpg images will be replaced by their "real" images. The purpose getting your html page loading faster (since those 250 companies all have the same "logo" in lazy.jpg :) ... But the JS takes care of it all after DOM finished loaded.

和wacka-wacka,所有lazy.jpg 图像都将被它们的“真实”图像替换。目的是让您的 html 页面加载速度更快(因为这 250 家公司在 lazy.jpg 中都有相同的“徽标”:)……但是在 DOM 完成加载后,JS 会处理这一切。

This is a jQuery solution of course. Can be done with pure js, as well.

这当然是一个 jQuery 解决方案。也可以用纯js来完成。

回答by str

Solution for 2020+:

2020+ 解决方案:

There is a native way to lazy load imagesthat already works in some browsers. While standardization is still underway, you can already use it today! Just add the loadingattribute to your image tags and set it to "lazy":

有一种本地方式来延迟加载图像,这种方式已经在某些浏览器中有效。虽然标准化仍在进行中,但您今天已经可以使用它了!只需将loading属性添加到您的图像标签并将其设置为“懒惰”:

<img
    src="picture.jpg"
    width="100"
    height="100"
    alt="descriptive text"
    loading="lazy"
>

And that's it. Compatible browsers will load that image lazily as soon as the current viewport is close enough.

就是这样。只要当前视口足够近,兼容的浏览器就会延迟加载该图像。

Further information available here:

此处提供更多信息:

If you need a solution for older browsers, you should have a look at Lazy loadingon MDN.

如果您需要旧浏览器的解决方案,您应该查看MDN上的延迟加载

回答by busy man

You can use justlazy, which is independent of dependencies like jQuery and very lightweight:

您可以使用justlazy,它独立于 jQuery 等依赖项并且非常轻量级:

The only call you need is:

您唯一需要的电话是:

var placeholders = document.querySelectorAll(".load-if-visible");
for (var i = 0; i < placeholders.length; ++i) {
  Justlazy.registerLazyLoad(placeholders[i]);
}

The placeholders have to be the following structure:

占位符必须是以下结构:

<span data-src="url/to/image" data-alt="some alt text"
      data-title="some title" class="load-if-visible">
</span>

For SEO reasons you can use any other placeholder (e.g. placeholder image).

出于 SEO 的原因,您可以使用任何其他占位符(例如占位符图像)。

Additionally there is a guide how to use it and some general things about lazy loading of images.

此外,还有一个如何使用它的指南以及一些关于延迟加载图像的一般信息。

回答by kok

There's many ways to implement lazy loading. The process is just that you load what you need. You can lazy load anything in the software scene. On websites most use it when loading in images and it's because most of the website is pretty much just images. I mean the artwork of the website plus the actual persons pictures they could have thousands of images on your server. This normally causes a slow down when you try and load all of them at the same time. At some point it starts to slow down the process. So, lazy loading is normally done for large websites. Like I said you can do this numerous ways. one way was already given. Have the img tag already loaded but the src part points to a dummy file something that is small in size. Don't use a image that is graphic or a picture... use something like a grey block.. or could use nothing. Then when the scroll part is near the scrolling point where the images are close by. It will run a function where it will replace the src with the real image link. Another way is to use ajax and the scroll point when close will append... load in the actual html code with the image in the src. This is what I actually use. I write a PHP file to lazy load images, data, text.

有很多方法可以实现延迟加载。这个过程就是你加载你需要的东西。您可以延迟加载软件场景中的任何内容。大多数网站在加载图像时使用它,这是因为大多数网站几乎只是图像。我的意思是网站的艺术作品加上实际人物的图片,他们可以在您的服务器上拥有数千张图片。当您尝试同时加载所有这些时,这通常会导致速度变慢。在某些时候,它开始减慢这个过程。因此,延迟加载通常用于大型网站。就像我说的,你可以通过多种方式做到这一点。已经给出了一种方法。已经加载了 img 标签,但 src 部分指向一个大小很小的虚拟文件。不要使用图形或图片的图像……使用灰色块之类的东西……或者什么都不用。然后当滚动部分靠近图像靠近的滚动点时。它将运行一个函数,用真实图像链接替换 ​​src。另一种方法是使用 ajax 和关闭时的滚动点将附加...加载实际的 html 代码,并在 src 中加载图像。这是我实际使用的。我写了一个 PHP 文件来延迟加载图像、数据、文本。

The whole point of this method is to download the files from a website when needed. When a image is loaded it's actually being downloaded from your server. So, the downloading process plus the actual loading time can increase when you start dealing with larger image files and too many of them.

这种方法的重点是在需要时从网站下载文件。加载图像时,它实际上是从您的服务器下载的。因此,当您开始处理较大的图像文件和过多的图像文件时,下载过程加上实际加载时间可能会增加。

回答by Apoorv Saxena

Lazy loading images using conventional way of attaching listener to scroll events or by making use of setInterval is highly non-performant as each call to getBoundingClientRect() forces the browser to re-layoutthe entire page and will introduce considerable jank to your website.

使用将侦听器附加到滚动事件的传统方式或通过使用 setInterval 延迟加载图像的性能非常低,因为每次调用 getBoundingClientRect() 都会强制浏览器重新布局整个页面,并且会给您的网站带来相当大的卡顿。

Use Lozad.js(just 569 bytes with no dependencies), which uses InteractionObserverto lazy load images performantly.

使用Lozad.js(只有 569 字节,没有依赖项),它使用InteractionObserver高效地延迟加载图像。