简体   繁体   English

延迟加载图片如何

[英]Lazy loading images how

I am developing an eshop .At products page based on category i putted some javascript based filtering.我正在开发一个 eshop。在基于类别的产品页面上,我放置了一些基于 javascript 的过滤。 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这个链接有类似的东西我做... 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...我的每个产品都需要半个killobyte,但图像是问题所在..所以我正在寻找如何延迟加载图像..由于我的页面与该站点不同,所以我认为加载仅对页面可见的图像是一个解决方案。然而,probem 是如何做到这一点,以便同时为 javascript 和非 javscript 启用的人工作.. 我唯一的解决方案是将链接存储在 css 类中,以某种方式为不可见产品的图像存储,如果在过滤更改后显示通过javascript图像src...非javascript用户没有这个问题,因为点击过滤器会将他们导航到其他页面...

Any other idea?还有其他想法吗?

Four options:四个选项:

Here are three options for you:这里有三个选项供您选择:

Use a background image使用背景图片

Kangkan's background answer has 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.您在评论中说您正在使用 jQuery。 There are lots of jQuery plug-ins for paging.有很多用于分页的 jQuery 插件。 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.它们的质量各不相同,因此您需要对它们进行测试并查看它们的代码,但我确信那里有一个质量不错的代码。

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.然后,您将拥有用于在结果页面之间移动的常用 UI 控件。 You'd have a server-side resource that returned HTML snippets or JSON-formatted data that you could use to populate that list.您将拥有一个服务器端资源,该资源返回可用于填充该列表的 HTML 片段或 JSON 格式的数据。 I'll use HTML for simplicity (although I'd probably use JSON in a production app, as it would tend to be smaller).为简单起见,我将使用 HTML(尽管我可能会在生产应用程序中使用 JSON,因为它往往更小)。 Each product entry is its own self-contained block:每个产品条目都是它自己的独立块:

<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.您使用 Ajax 请求页面并使用 JavaScript 更新产品列表。 Since you've said you use jQuery, this can be be trivially simple:既然你说你使用 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-xyz attribute 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 img to 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');
}

Edit In a comment elsewhere you said you're using jQuery.编辑在其他地方的评论中,您说您正在使用 jQuery。 If so, a translation of the above might look like this:如果是这样,上面的翻译可能如下所示:

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

References (w3.org):参考资料(w3.org):

Off-topic, but a lot of this stuff gets a lot easier if you use a JavaScript library like jQuery , Closure , Prototype , YUI , or any of several others to smooth over the rough edges for you.题外话,但是如果您使用 JavaScript 库(如jQueryClosurePrototypeYUI其他几个库中的任何一个)来为您平滑粗糙的边缘,那么很多这些东西会变得容易得多 (You've since said you're using jQuery.) (你已经说过你在使用 jQuery。)

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.如果您只是希望缓慢加载图像并首先加载页面的其余部分,您可以将图像作为背景而不使用<img>标签。 If you use the <img> tag, the image is loaded at the time of loading the page and so the page load becomes slow.如果使用<img>标签,图片会在加载页面时加载,因此页面加载会变慢。 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.用户可以阅读文本并在一段时间后看到加载的图像。

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

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.我使用了 JQuery: 1. 命名所有类,其中你想用相同的名称延迟加载,比如“async” 2. 将真实图像位置从 'src' 复制到 'alt' 属性 3. 完成页面加载后,我的脚本将复制所有 'alt' 值到 'src' 看例子。 This is full working sample html:这是完整的工作示例 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/

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?我的问题是:如今有多少访问者没有启用 Javascript? 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;在任何情况下,这些人都习惯于禁用 javascript 时网站无法完全正常运行; your site will actually be better than most if the only difference they have to put up with is slower loading speed.如果他们必须忍受的唯一区别是加载速度较慢,那么您的网站实际上会比大多数网站更好。

(ps - I presume you're using Jquery's LazyLoad plugin for the Javascript enabled people?) (ps - 我假设您正在为启用 Javascript 的人使用Jquery 的 LazyLoad 插件?)

EDIT: I reread your question & noticed you also want this to work for people with Javascript disabled!编辑:我重读了你的问题并注意到你也希望这对禁用 Javascript 的人有用! Then yes my answer is not acceptable - but I'll leave it for the record.那么是的,我的回答是不可接受的 - 但我会留下记录。

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.重要提示:我仍在研究哪些 Javascript 库最适合使用。 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 .我的要求通常是: licensedependenciesbrowser supportdevice supportweightcommunityhistory

Browser level support浏览器级别支持

Modern browsers have the ability to load images lazy using loading="lazy" attribute!现代浏览器能够使用loading="lazy"属性loading="lazy"加载图像!

<img src="image.png" loading="lazy" alt="…" width="200" height="200">

For more information, visit here .如需更多信息,请访问此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM