javascript 延迟加载图片如何

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

Lazy loading images how

javascripthtmlcsslazy-loadinglazy-evaluation

提问by GorillaApe

I am developing an eshop .At products page based on category i putted some javascript based filtering. However a problem arises if a category has a lot of products. This link has something similar i do ... http://www.snowandrock.com/sunglasses/snowboard/fcp-category/list?resetFilters=true

我正在开发一个 eshop。在基于类别的产品页面上,我放置了一些基于 javascript 的过滤。但是,如果一个类别有很多产品,就会出现问题。这个链接有类似的东西我做... http://www.snowandrock.com/sunglasses/snowboard/fcp-category/list?resetFilters=true

How ever this page is painfully slow and is over 2mb !!!

这个页面是多么的缓慢,而且超过 2mb !!!

Every product for me needs half killobyte but the image is the problem.. So i am looking how to lazy load images.. Since my page has pagination unlike that site i think that loading images that are visible only to the page is a solution.The probem however is how to do it in order to work both for javascript and non javscript enabled people.. The only solution i though is storing the link at the css class somehow of the image for the non visible products and if shown after filtering change via javascript the image src... Non javascript users dont have this problem as clicking on a filter would navigate them to other page...

我的每个产品都需要半个字节,但图像是问题所在.. 所以我正在寻找如何延迟加载图像.. 由于我的页面与该站点不同,我认为加载仅对页面可见的图像是一个解决方案。然而,probem 是如何做到这一点,以便为启用 javascript 和非 javscript 的人工作。我唯一的解决方案是将链接存储在 css 类中,以某种方式为不可见产品的图像存储,如果在过滤更改后显示通过javascript图像src...非javascript用户没有这个问题,因为点击过滤器会将他们导航到其他页面...

Any other idea?

还有其他想法吗?

采纳答案by T.J. Crowder

Four options:

四个选项:

Here are three options for you:

这里有三个选项供您选择:

Use a background image

使用背景图片

Kangkan's background answerhas this covered.

康坎的背景回答涵盖了这一点。

If that doesn't work for you, I'm assuming you only need help with the JavaScript-enabled stuff, since you said the non-JavaScript users will see a different page.

如果这对您不起作用,我假设您只需要启用 JavaScript 的帮助,因为您说非 JavaScript 用户将看到不同的页面。

Use a plug-in

使用插件

Paging has been done. You've said in a comment that you're using jQuery. There are lots of jQuery plug-ins for paging. Find one you like, and use it. They will be of varying quality, so you'll want to test them out and review their code, but I'm sure there's a decent-quality one out there.

分页已经完成。您在评论中说您正在使用 jQuery。有很多用于分页的 jQuery 插件。找到一个你喜欢的,并使用它。它们的质量各不相同,因此您需要对它们进行测试并检查它们的代码,但我确信那里有一个质量不错的代码。

Server-side Paging

服务器端分页

This is where the main page loads either without any products at all, or with only the first page of products. Typically you'd put all of the products into a container, like this:

这是主页加载根本没有任何产品或只有第一页产品的地方。通常,您会将所有产品放入一个容器中,如下所示:

<ul id='productList'>
</ul>

Then you'd have the usual UI controls for moving amongst the pages of results. You'd have a server-side resource that returned HTML snippets or JSON-formatted data that you could use to populate that list. I'll use HTML for simplicity (although I'd probably use JSON in a production app, as it would tend to be smaller). Each product entry is its own self-contained block:

然后,您将拥有用于在结果页面之间移动的常用 UI 控件。您将拥有一个服务器端资源,该资源返回可用于填充该列表的 HTML 片段或 JSON 格式的数据。为简单起见,我将使用 HTML(尽管我可能会在生产应用程序中使用 JSON,因为它往往更小)。每个产品条目都是它自己的独立块:

<li id='product-001'>
  <div>This is Product 001</div>
  <img src='http://www.gravatar.com/avatar/88ca83ed97a129596d6e8dd86deef994?s=32&d=identicon&r=PG'>
  <div>Blurb about Product 001</div>
</li>

...and then the page returns as many of these as you think is appropriate. You request the page using Ajax and update the product list using JavaScript. Since you've said you use jQuery, this can be be trivially simple:

...然后页面会返回您认为合适的尽可能多的这些。您使用 Ajax 请求页面并使用 JavaScript 更新产品列表。既然您已经说过您使用 jQuery,那么这可能非常简单:

$('#productList').load("/path/to/paging/page?start=X&count=Y");

Here's an example prototype(not production code); it fakes the Ajax because JSBin was giving me Ajax issues.

这是一个示例原型(不是生产代码);它伪造了 Ajax,因为 JSBin 给了我 Ajax 问题。

One big page download, then client-side JavaScript paging

一个大页面下载,然后客户端 JavaScript 分页

I'm not sure how you're doing your filtering, but if you have an element that contains the product information, you can store the image URL in a data-xyzattribute on it:

我不确定你是如何进行过滤的,但如果你有一个包含产品信息的元素,你可以将图像 URL 存储data-xyz在它的属性中:

<div id='product-123' data-image='/images/foo.png'>

Then when your code makes that visible, you can easily add an imgto it:

然后,当您的代码使其可见时,您可以轻松地img向其中添加一个:

var prod, imgsrc, img;
prod = document.getElementById('product-123');
prod.style.display = 'block'; // Or whatever you're doing to show it
imgsrc = prod.getAttribute('data-image');
if (imgsrc) {
    img = document.createElement('img');
    img.src = imgsrc;
    prod.appendChild(img); // You'd probably put this somewhere else, but you get the idea
    prod.removeAttribute('data-image');
}

EditIn a comment elsewhere you said you're using jQuery. If so, a translation of the above might look like this:

编辑在其他地方的评论中,您说您正在使用 jQuery。如果是这样,上面的翻译可能如下所示:

var prod, imgsrc, img;
prod = $('#product-123');
prod.show();
imgsrc = prod.attr('data-image');
if (imgsrc) {
    $("<img/>").attr('src', imgsrc).appendTo(prod); // You'd probably put this somewhere else, but you get the idea
    prod.removeAttr('data-image');
}

No need to remove it again when hiding, since the image will already be shown, which is why I remove the attribute once we've used it.

隐藏时无需再次删除它,因为图像已经显示,这就是为什么我在使用它后删除该属性。

The reason I've used the data-prefix is validation: As of HTML5, you can define your owwn data-xyzattributes and your pages will still pass validation. In earlier versions of HTML, you were not allowed to define your own attributes (although in practice no major browser cares) and so if you used your own attribute for this, the page wouldn't validate.

我使用data-前缀的原因是验证:从 HTML5 开始,您可以定义自己的data-xyz属性,并且您的页面仍将通过验证。在早期版本的 HTML 中,不允许您定义自己的属性(尽管实际上主流浏览器并不关心),因此如果您为此使用自己的属性,页面将无法验证。

References (w3.org):

参考资料(w3.org):

Off-topic, but a lotof this stuff gets a lot easier if you use a JavaScript library like jQuery, Closure, Prototype, YUI, or any of several othersto smooth over the rough edges for you.(You've since said you're using jQuery.)

题外话,但是如果您使用 JavaScript 库(如jQueryClosurePrototypeYUI其他几个库中的任何一个)来为您平滑粗糙的边缘,那么很多这些东西会变得容易得多(你已经说过你在使用 jQuery。)

回答by Kangkan

If you simply wish to load the images slowly and the rest of the page gets loaded first, you can put the images as background and not use the <img>tag. If you use the <img>tag, the image is loaded at the time of loading the page and so the page load becomes slow. However, the background images loads after the page is shown to the user. The user can read the text and see the images loading after some time.

如果您只是希望缓慢加载图像并首先加载页面的其余部分,则可以将图像作为背景而不使用<img>标签。如果使用该<img>标签,图像会在加载页面时加载,因此页面加载会变慢。但是,在向用户显示页面后加载背景图像。用户可以阅读文本并在一段时间后看到加载的图像。

回答by Spudley

I'm fairly certain it's not possible in plain HTML without some kind of Javascript intervention.

我相当肯定,如果没有某种 Javascript 干预,在纯 HTML 中是不可能的。

After all, if it was possible to do it without scriping, why would anyone have implemented it in Javascript in the first place?

毕竟,如果没有脚本就可以做到这一点,那么为什么有人首先在 Javascript 中实现它呢?

My question is: How many visitors do you get who these days don't have Javascript enabled? I bet it's very few. And in any case, those people are used to sites not being fully functional when they have javascript disabled; your site will actually be better than most if the only difference they have to put up with is slower loading speed.

我的问题是:现在有多少访问者没有启用 Javascript?我敢打赌它很少。在任何情况下,这些人都习惯于禁用 javascript 时网站无法完全正常运行;如果他们必须忍受的唯一区别是加载速度较慢,那么您的网站实际上会比大多数网站更好。

(ps - I presume you're using Jquery's LazyLoad pluginfor the Javascript enabled people?)

(ps - 我假设您正在为启用 Javascript 的人使用Jquery 的 LazyLoad 插件?)

回答by Pavel Podlipensky

I'd suggest to implement responsive image approachin order to avoid huge image files on devices which cannot display it properly (or human can't tell the difference).

我建议实施响应式图像方法,以避免设备上无法正确显示的巨大图像文件(或人类无法区分)。

回答by Jeff_Alieffson

I wrote the following code for my own site. I used JQuery: 1. Name all classes, where U want lazy loading by the same name, say "async" 2. Copy the real image location from 'src' to 'alt' attribute 3. After finishing page loading my script will copy all 'alt' values into 'src' Look at example. This is full working sample html:

我为我自己的网站编写了以下代码。我使用了 JQuery: 1. 命名所有类,其中你想用相同的名称延迟加载,比如“async” 2. 将真实图像位置从 'src' 复制到 'alt' 属性 3. 完成页面加载后,我的脚本将复制所有 'alt' 值到 'src' 看例子。这是完整的工作示例 html:

<html> 
<head> 
<script src="http://code.jquery.com/jquery-1.9.1.js"></script> 
<script type="text/javascript">
        $(document).ready(function(){
            $('img.async').each(function(i, ele) {
                 $(ele).attr('src',$(ele).attr('alt'));
            });
        });
        </script> </head> <body> <img class="async" title="Гороскопы" alt="http://virtual-doctor.net/images/horoscopes.jpg" width="135" height="135"/> 
</body>
</html>

You can feel the speed in real site, where I used it http://virtual-doctor.net/

你可以在真实站点中感受到速度,我在那里使用过 http://virtual-doctor.net/

回答by Adrien Be

EDIT:I reread your question & noticed you also want this to work for people with Javascript disabled! Then yes my answer is not acceptable - but I'll leave it for the record.

编辑:我重读了你的问题并注意到你也希望这对禁用 Javascript 的人有用!那么是的,我的回答是不可接受的 - 但我会保留它。

Here are some Javascript libraries for Image Lazy Loading.

下面是一些用于图像延迟加载的 Javascript 库。

They help you load the images needed when the elements 'would' be in view by simply changing the image src attribute.

当元素“将”在视图中时,它们可以帮助您加载所需的图像,只需更改图像 src 属性。

Important: I am still investigating which of these Javascript libraries is best to use. Do your homework I'd say, take some time to search what's the best tool for the job. My requirements are usually: license, dependencies, browser support, device support, weight, community, and history.

重要提示:我仍在研究哪些 Javascript 库最适合使用。做你的功课,我会说,花一些时间来寻找最适合这项工作的工具。我的要求通常是:licensedependenciesbrowser supportdevice supportweightcommunity,和history