js 方法延时 加载_延迟加载图像以提高网站性能的五种方法

js 方法延时 加载

With images being among the most popular type of content on the web, page load time on websites can easily become an issue.

由于图像是Web上最受欢迎的内容之一,因此网站上的页面加载时间很容易成为问题。

Even when properly optimized, images can weigh quite a bit. This can have a negative impact on the time visitors have to wait before they can access content on your website. Chances are, they get impatient and navigate somewhere else, unless you come up with a solution to image loading that doesn’t interfere with the perception of speed.

即使进行了适当的优化 ,图像也可能占很大的比重。 这会对访问者必须等待才能访问您网站上的内容的时间产生负面影响。 除非您想出一种不会影响速度感知的图像加载解决方案,否则它们很可能会耐心地在其他地方导航。

In this article, you’ll learn about five approaches to lazy loading images that you can add to your web optimization toolkit to improve the user experience on your website.

在本文中,您将了解五种延迟加载图像的方法,可以将其添加到Web优化工具包中以改善网站上的用户体验。

什么是延迟加载? (What Is Lazy Loading?)

Lazy loading images means loading images on websites asynchronously — that is, after the above-the-fold content is fully loaded, or even conditionally, only when they appear in the browser’s viewport. This means that if users don’t scroll all the way down, images placed at the bottom of the page won’t even be loaded.

延迟加载图像是指异步加载网站上的图像-也就是说,在上述内容完全加载后,甚至有条件地,仅当它们出现在浏览器的视口中时。 这意味着,如果用户没有完全向下滚动,则位于页面底部的图像甚至都不会被加载。

A number of websites use this approach, but it’s especially noticeable on image-heavy sites. Try browsing your favorite online hunting ground for high-res photos, and you’ll soon realize how the website loads just a limited number of images. As you scroll down the page, you’ll see placeholder images quickly filling up with real images for preview. For instance, notice the loader on Unsplash.com: scrolling that portion of the page into view triggers the replacement of a placeholder with a full-res photo:

许多网站都使用这种方法,但是在图片繁多的网站上尤其明显。 尝试浏览您喜欢的在线狩猎场以获取高分辨率照片,您很快就会意识到该网站仅加载有限数量的图像的方式。 向下滚动页面时,您会看到占位符图像Swift填充真实图像进行预览。 例如,请注意Unsplash.com上的加载程序:将页面的该部分滚动到视图中会触发使用全分辨率照片替换占位符:

Lazy loading in action on Unsplash.com

为什么要关心延迟加载图像? (Why Should You Care About Lazy Loading Images?)

There are at least a couple of excellent reasons why you should consider lazy loading images for your website:

至少有两个极好的原因,您应该考虑为网站延迟加载图像:

  • If your website uses JavaScript to display content or provide some kind of functionality to users, loading the DOM quickly becomes critical. It’s common for scripts to wait until the DOM has completely loaded before they start running. On a site with a significant number of images, lazy loading — or loading images asynchronously — could make the difference between users staying or leaving your website.

    如果您的网站使用JavaScript来显示内容或向用户提供某种功能,则快速加载DOM变得至关重要。 脚本通常要等到DOM完全加载后才能开始运行。 在包含大量图像的网站上,延迟加载(或异步加载图像)可能会导致用户停留或离开您的网站有所不同。
  • Since most lazy loading solutions work by loading images only if the user has scrolled to the location where images would be visible inside the viewport, those images will never be loaded if users never get to that point. This means considerable savings in bandwidth, for which most users, especially those accessing the Web on mobile devices and slow-connections, will be thanking you.

    由于大多数延迟加载解决方案都是通过仅在用户滚动到在视口内可见图像的位置时才加载图像来工作的,因此如果用户从未到达该点,则将永远不会加载这些图像。 这意味着可以节省大量带宽,为此,大多数用户,特别是那些在移动设备上访问Web且连接缓慢的用户,将非常感谢您。

Well, lazy loading images helps with website performance, but what’s the best way to go about it?

好吧,延迟加载图像有助于提高网站性能,但是最好的解决方法是什么?

There’s no perfect way.

没有完美的方法。

If you live and breathe JavaScript, implementing your own lazy loading solution shouldn’t be an issue. Nothing gives you more control than coding something yourself.

如果您生活和呼吸JavaScript,那么实现自己的延迟加载解决方案就不会成为问题。 没有什么比您自己编写代码给您更多的控制权了。

Alternatively, you can browse the Web for viable approaches and start experimenting with them. I did just that and came across these five interesting techniques.

或者,您可以浏览Web以找到可行的方法并开始进行试验。 我就是这样做的,并遇到了这五种有趣的技术。

#1本机延迟加载 (#1 Native Lazy Loading)

Native lazy loading of images and iframes is super cool. Nothing could be more straightforward than the markup below:

图像和iframe的本机延迟加载非常酷。 没有什么比下面的标记更直接了:

<img src="myimage.jpg" loading="lazy" alt="..." />
<iframe src="content.html" loading="lazy"></iframe>

As you can see, no JavaScript, no dynamic swapping of the src attribute’s value, just plain old HTML.

如您所见,没有JavaScript,没有src属性值的动态交换,只是普通的旧HTML。

The loading attribute gives us the option to delay off-screen images and iframes until users scroll to their location on the page. loading can take any of these three values:

loading属性使我们可以选择延迟屏幕外图像和iframe,直到用户滚动到页面上的位置为止。 loading可以采用以下三个值之一:

  • lazy: works great for lazy loading

    lazy :非常适合延迟加载

  • eager: instructs the browser to load the specified content right away

    eager :指示浏览器立即加载指定的内容

  • auto: leaves the option to lazy load or not to lazy load up to the browser.

    auto :将选项保留为延迟加载或不延迟加载至浏览器。

This method has no rivals: it has zero overhead, it’s clean and simple. However, although at the time of writing most major browsers have good support for the loading attribute, not all browsers are on board yet.

这种方法无可匹敌:它的开销为零,简洁明了。 但是,尽管在撰写本文时,大多数主流浏览器都loading属性提供了很好的支持,但并不是所有浏览器都支持

For an in-depth article on this awesome feature for lazy-loading images, including browser support workarounds, don’t miss Addy Osmani’s “Native image lazy-loading for the web!”.

要获得有关此令人敬畏的延迟加载图像功能的深入文章,包括浏览器支持的解决方法,请不要错过Addy Osmani的“ Web的本地图像延迟加载! ”。

#2使用Intersection Observer API进行延迟加载 (#2 Lazy Loading Using the Intersection Observer API)

The Intersection Observer API is a modern interface that you can leverage for lazy loading images and other content.

Intersection Observer API是一个现代化的接口,您可以利用它来延迟加载图像和其他内容。

Here’s how MDN introduces this API:

MDN引入此API的方法如下:

The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document’s viewport.

Intersection Observer API提供了一种异步观察目标元素与祖先元素或顶级文档的视口相交的变化的方法。

In other words, what’s being asynchronously watched is the intersection of one element with another.

换句话说,异步监视的是一个元素与另一个元素的交集。

Denys Mishunov has a great tutorial both on the Intersection Observer and on lazy loading images using it. Here’s what his solution looks like.

Denys Mishunov在Intersection Observer和使用它延迟加载图像方面都有很好的教程。 这是他的解决方案。

Let’s say you’d like to lazy load an image gallery. The markup for each image would look like this:

假设您要延迟加载图片库。 每个图像的标记如下所示:

<img data-src="image.jpg" alt="test image">

Notice how the path to the image is contained inside a data-src attribute, not a src attribute. The reason is that using src means the image would load right away, which is not what you want.

请注意,图像的路径是如何包含在data-src属性而不是src属性中的。 原因是使用src意味着图像将立即加载,这不是您想要的。

In the CSS, you give each image a min-height value, let’s say 100px. This gives each image placeholder (the img element without the src attribute) a vertical dimension:

在CSS中,为每个图像指定一个min-height值,例如100px 。 这为每个图像占位符(不带src属性的img元素)提供了一个垂直尺寸:

img {
  min-height: 100px;
  /* more styles here */
}

In the JavaScript document, you then create a config object and register it with an intersectionObserver instance:

然后,在JavaScript文档中,创建一个config对象,并向intersectionObserver实例注册它:

// create config object: rootMargin and threshold
// are two properties exposed by the interface
const config = {
  rootMargin: '0px 0px 50px 0px',
  threshold: 0
};

// register the config object with an instance
// of intersectionObserver
let observer = new intersectionObserver(function(entries, self) {
  // iterate over each entry
  entries.forEach(entry => {
    // process just the images that are intersecting.
    // isIntersecting is a property exposed by the interface
    if(entry.isIntersecting) {
      // custom function that copies the path to the img
      // from data-src to src
      preloadImage(entry.target);
      // the image is now in place, stop watching
      self.unobserve(entry.target);
    }
  });
}, config);

Finally, you iterate over all of your images and add them to this iterationObserver instance:

最后,您遍历所有图像并将它们添加到该iterationObserver实例中:

const imgs = document.querySelectorAll('[data-src]');
imgs.forEach(img => {
  observer.observe(img);
});

The merits of this solution: it’s a breeze to implement, it’s effective, and has the intersectionObserver do the heavy-lifting in terms of calculations.

该解决方案的优点:实现起来轻而易举,非常有效,并且可以让intersectionObserver观察员在计算方面进行繁重的工作。

On the flip side, although the Intersection Observer API is supported by most browsers in their latest versions, it’s not consistently supported by all of them. Fortunately, a polyfill is available.

另一方面,尽管大多数浏览器都支持最新版本的Intersection Observer API,但并非所有浏览器都始终支持该API。 幸运的是,可以使用polyfill

You can learn more on the Intersection Observer API and the details of this implementation in Denys’s article.

您可以在Denys的文章中了解有关Intersection Observer API的更多信息以及此实现的详细信息。

#3 Lozad.js (#3 Lozad.js)

A quick and easy alternative for implementing lazy loading of images is to let a JS library do most of the job for you.

实现图像的延迟加载的一种快速简便的替代方法是让JS库为您完成大部分工作。

Lozad is a highly performant, light and configurable lazy loader in pure JavaScript with no dependencies. You can use it to lazy load images, videos, iframes and more, and it uses the Intersection Observer API.

Lozad是纯JavaScript中的高性能,轻量且可配置的惰性加载器,没有任何依赖关系。 您可以使用它来延迟加载图像,视频,iframe等,并且它使用Intersection Observer API。

You can include Lozad with npm/Yarn and import it using your module bundler of choice:

您可以将Lozad包含在npm / Yarn中,并使用所选的模块捆绑器将其导入:

npm install --save lozad

yarn add lozad
import lozad from 'lozad';

Alternatively, you can simply download the library using a CDN and add it to the bottom of the HTML page in a < script> tag:

另外,您可以简单地使用CDN下载该库并将其添加到< script>标记HTML页面底部:

<script src="https://cdn.jsdelivr.net/npm/lozad/dist/lozad.min.js"></script>

Next, for a basic implementation, add the class lozad to the asset in your markup:

接下来,对于基本实现,将lozad添加到标记中的资产:

<img class="lozad" data-src="img.jpg">

Finally, instantiate Lozad in your JS document:

最后,在您的JS文档中实例化Lozad:

const observer = lozad();
observer.observe();

You’ll find all the details of how you can use the library on the Lozad GitHub repository.

您将在Lozad GitHub存储库中找到有关如何使用该库的所有详细信息

If you don’t want to dive into the workings of the Intersection Observer API or you’re simply looking for a fast implementation that applies to a variety of content types, Lozad is a great choice.

如果您不想深入了解Intersection Observer API的工作原理,或者只是在寻找适用于各种内容类型的快速实现,则Lozad是一个不错的选择。

Only, be mindful of browser support and eventually integrate this library with a polyfill for the Intersection Observer API.

仅注意浏览器支持,并最终将此库与用于Intersection Observer API的polyfill集成。

#4延迟加载具有模糊的图像效果 (#4 Lazy Loading with Blurred Image Effect)

If you’re a Medium reader, you have certainly noticed how the site loads the main image inside a post.

如果您是中级读者,那么您肯定已经注意到该站点如何在帖子中加载主图像。

The first thing you see is a blurred, low-resolution copy of the image, while its high-res version is being lazy loaded:

您首先看到的是图像的模糊,低分辨率副本,而其高分辨率版本则被延迟加载:

Blurred placeholder image on Medium website
Blurred placeholder image on Medium website
中型网站上的占位符图像模糊
High-res, lazy loaded image on Medium website.
High-res, lazy loaded image on Medium website
中等网站上的高分辨率,延迟加载的图像

You can lazy load images with this interesting blurring effect in a number of ways.

您可以通过多种方式来延迟加载具有这种有趣的模糊效果的图像。

My favorite technique is by Craig Buckler. Here’s all the goodness of this solution:

我最喜欢的技术是Craig Buckler。 这是此解决方案的所有优点:

  • Performance: only 463 bytes of CSS and 1,007 bytes of minified JavaScript code

    性能:仅463字节CSS和1,007字节的最小JavaScript代码
  • Support for retina screens

    支持视网膜屏幕
  • Dependency-free: no jQuery or other libraries and frameworks required

    无依赖关系:不需要jQuery或其他库和框架
  • Progressively enhanced to counteract older browsers and failing JavaScript

    逐步增强功能以​​抵消较旧的浏览器和JavaScript失败

You can read all about it in How to Build Your Own Progressive Image Loader and download the code on the project’s GitHub repo.

您可以在如何构建自己的渐进式图像加载器中阅读有关它的全部信息,并在项目的GitHub存储库上下载代码。

#5 Yall.js (#5 Yall.js)

Yall is a feature-packed, lazy-loading script for images, videos, and iframes. More specifically, it uses the Intersection Observer API and smartly falls back on traditional event handler techniques where necessary.

Yall是功能丰富的延迟加载脚本,用于图像,视频和iframe。 更具体地说,它使用Intersection Observer API并在必要时巧妙地使用传统的事件处理程序技术。

When including Yall in your document, you need to initialize it as follows:

在文档中包含Yall时,需要按以下方式对其进行初始化:

<script src="yall.min.js"></script>
<script>
  document.addEventListener("DOMContentLoaded", yall);
</script>

Next, to lazy load a simple img element, all you need to do in your markup is:

接下来,要延迟加载一个简单的img元素,您在标记中需要做的就是:

<img class="lazy" src="placeholder.jpg" data-src="image-to-lazy-load.jpg" alt="Alternative text to describe image.">

Note the following:

请注意以下几点:

  • you add the class lazy to the element

    您将懒惰的类添加到元素

  • the value of src is a placeholder image

    src的值是一个占位符图像

  • the path to the image you want to lazy load is inside the data-src attribute

    您要延迟加载的图像的路径在data-src属性内

Among the benefits of Yall are:

Yall的好处包括:

  • great performance with the Intersection Observer API

    Intersection Observer API的出色性能
  • fantastic browser support (it goes back to IE11)

    出色的浏览器支持(可回溯到IE11)
  • no other dependencies necessary

    无需其他依赖

To learn more about what Yall can offer and for more complex implementations, feel free to check out the project’s page on GitHub.

要了解有关Yall可以提供的内容以及更复杂的实现的更多信息,请随时查看GitHub上项目页面

结论 (Conclusion)

And there you have it — five ways of lazy loading images you can start to experiment with and test out in your projects.

到此为止,您可以使用以下五种延迟加载图像的方式开始尝试并在项目中进行测试。

翻译自: https://www.sitepoint.com/five-techniques-lazy-load-images-website-performance/

js 方法延时 加载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值