Javascript 当用户将图像滚动到视图中时如何动态(或延迟)加载图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5117421/
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
How to load images dynamically (or lazily) when users scrolls them into view
提问by Salman A
I've noticed this in numerous "modern" websites (e.g. facebook and google image search) where the images below the fold load only when user scrolls down the page enough to bring them inside the visible viewport region (upon view source, the page shows Xnumber of <img>
tags but they are not fetched from the server straight away). What is this technique called, how does it work and in how many browsers does it work. And is there a jQuery plugin that can achieve this behavior with minimum coding.
我已经在许多“现代”网站(例如 facebook 和 google 图像搜索)中注意到这一点,其中折叠下方的图像仅当用户向下滚动页面足以将它们带入可见视口区域时<img>
才会加载(在查看源时,页面显示X个标签,但它们不会立即从服务器获取)。这种技术叫什么,它是如何工作的以及它在多少浏览器中工作。是否有一个 jQuery 插件可以用最少的编码实现这种行为。
Edit
编辑
Bonus: can someone explain if there is a "onScrolledIntoView" or similar event for HTML elements. If not, how do these plugins work?
奖励:有人可以解释一下 HTML 元素是否有“onScrolledIntoView”或类似事件。如果没有,这些插件如何工作?
采纳答案by Alec Smart
Some of the answers here are for infinite page. What Salman is asking is lazy loading of images.
这里的一些答案适用于无限页面。Salman 要求的是延迟加载图像。
EDIT: How do these plugins work?
编辑:这些插件如何工作?
This is a simplified explanation:
这是一个简化的解释:
- Find window size and find the position of all images and their sizes
- If the image is not within the window size, replace it with a placeholder of same size
- When user scrolls down, and position of image < scroll + window height, the image is loaded
- 查找窗口大小并找到所有图像的位置及其大小
- 如果图像不在窗口大小范围内,请将其替换为相同大小的占位符
- 当用户向下滚动,并且图像位置 < 滚动 + 窗口高度时,图像被加载
回答by Annika Backstrom
Dave Artz of AOL gave a great talk on optimization at jQuery Conference Boston last year. AOL uses a tool called Sonar for on-demand loading based on scroll position. Check the code for the particulars of how it compares scrollTop (and others) to the element offset to detect if part or all of the element is visible.
AOL 的 Dave Artz 去年在波士顿 jQuery 大会上发表了关于优化的精彩演讲。AOL 使用名为 Sonar 的工具根据滚动位置进行按需加载。检查代码以了解它如何将 scrollTop(和其他)与元素偏移量进行比较的细节,以检测元素的部分或全部是否可见。
Dave talks about Sonar in these slides. Sonar starts on slide 46, while the overall "load on demand" discussion starts on slide 33.
Dave 在这些幻灯片中谈到了声纳。声纳从幻灯片 46 开始,而整体“按需加载”讨论从幻灯片 33 开始。
回答by Hastig Zusammenstellen
I came up with my own basic method which seems to work fine (so far). There's probably a dozen things some of the popular scripts address that I haven't thought of.
我想出了我自己的基本方法,它似乎工作正常(到目前为止)。一些流行的脚本可能有很多我没有想到的东西。
Note- This solution is fast and easy to implement but of course not great for performance. Definitely look into the new Intersection Observeras mentioned by Apoorvand explained by developers.googleif performance is an issue.
注意- 此解决方案快速且易于实施,但当然对性能不利。当然考虑新的十字路口观察由提到Apoorv和解释developers.google如果性能是一个问题。
The JQuery
JQuery
$(window).scroll(function() {
$.each($('img'), function() {
if ( $(this).attr('data-src') && $(this).offset().top < ($(window).scrollTop() + $(window).height() + 100) ) {
var source = $(this).data('src');
$(this).attr('src', source);
$(this).removeAttr('data-src');
}
})
})
Sample html code
示例 html 代码
<div>
<img src="" data-src="pathtoyour/image1.jpg">
<img src="" data-src="pathtoyour/image2.jpg">
<img src="" data-src="pathtoyour/image3.jpg">
</div>
Explained
解释
When the page is scrolled each image on the page is checked..
当页面滚动时,页面上的每个图像都会被检查..
$(this).attr('data-src')
- if the image has the attribute data-src
$(this).attr('data-src')
- 如果图像具有属性 data-src
and how far those images are from the bottom of the window..
以及这些图像离窗口底部有多远..
$(this).offset().top < ($(window).scrollTop() + $(window).height() + 100)
$(this).offset().top < ($(window).scrollTop() + $(window).height() + 100)
adjust the + 100 to whatever you like (- 100 for example)
将 + 100 调整为您喜欢的任何值(例如 - 100)
var source = $(this).data('src');
- gets the value of data-src=
aka the image url
var source = $(this).data('src');
- 获取data-src=
aka 图像 url的值
$(this).attr('src', source);
- puts that value into the src=
$(this).attr('src', source);
- 将该值放入 src=
$(this).removeAttr('data-src');
- removes the data-src attribute (so your browser doesn't waste resources messing with the images that have already loaded)
$(this).removeAttr('data-src');
- 删除 data-src 属性(这样你的浏览器就不会浪费资源来处理已经加载的图像)
Adding To Existing Code
添加到现有代码
To convert your html, in an editor just search and replace src="
with src="" data-src="
要转换您的 html,只需在编辑器中搜索并替换src="
为src="" data-src="
回答by jwegner
There is a pretty nice infinite scroll plugin here
有一个相当不错的无限滚动的插件这里
I've never programmed one myself, but I would imagine this is how it works.
我从来没有自己编程过,但我想这就是它的工作原理。
An event is bound to the the window scrolling
$(window).scroll(myInfinteScrollFunction);
The called function checks if scroll top is greater than the window size
function myInfiniteScrollFunction() { if($(window).scrollTop() == $(window).height()) makeAjaxRequest(); }
An AJAX request is made, specifying which result # to start at, how many to grab, and any other parameters necessary for the data pull.
$.ajax({ type: "POST", url: "myAjaxFile.php", data: {"resultNum": 30, "numPerPage": 50, "query": "interesting%20icons" }, success: myInfiniteLoadFunction(msg) });
The ajax returns some (most-likely JSON formatted) content, and passes them into the loadnig function.
一个事件绑定到窗口滚动
$(window).scroll(myInfinteScrollFunction);
被调用的函数检查滚动顶部是否大于窗口大小
function myInfiniteScrollFunction() { if($(window).scrollTop() == $(window).height()) makeAjaxRequest(); }
发出 AJAX 请求,指定从哪个结果开始,获取多少,以及数据拉取所需的任何其他参数。
$.ajax({ type: "POST", url: "myAjaxFile.php", data: {"resultNum": 30, "numPerPage": 50, "query": "interesting%20icons" }, success: myInfiniteLoadFunction(msg) });
ajax 返回一些(最有可能是 JSON 格式的)内容,并将它们传递给 loadnig 函数。
Hope that makes sense.
希望这是有道理的。
回答by Apoorv Saxena
Lazy loading images by 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 IntersectionObserverto lazy load images performantly.
使用Lozad.js(只有 569 字节,没有依赖项),它使用IntersectionObserver高效地延迟加载图像。
回答by Arnaud Meuret
The Swiss Army knife of image lazy loading is YUI's ImageLoader.
图像延迟加载的瑞士军刀是 YUI 的ImageLoader。
Because there is more to this problem than simply watching the scroll position.
因为这个问题不仅仅是简单地观察滚动位置。
回答by Cliff Ribaudo
Im using jQuery Lazy. It took me about 10 minutes to test out and an hour or two to add to most of the image links on one of my websites (CollegeCarePackages.com). I have NO (none/zero)relationship of any kind to the dev, but it saved me a lot of time and basically helped improve our bounce rate for mobile users and I appreciate it.
我使用jQuery Lazy。我花了大约 10 分钟进行测试,并花了一两个小时添加到我的一个网站 ( CollegeCarePackages.com)上的大多数图像链接。我与开发人员没有任何(无/零)关系,但它为我节省了大量时间,并且基本上帮助提高了移动用户的跳出率,我很感激。
回答by vebs
This Link work for me demo
此链接适用于我的演示
1.Load the jQuery loadScroll plugin after jQuery library, but before the closing body tag.
1.在jQuery库之后,但在关闭body标签之前加载jQuery loadScroll插件。
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script><script src="jQuery.loadScroll.js"></script>
2.Add the images into your webpage using Html5 data-src attribute. You can also insert placeholders using the regular img's src attribute.
2.使用 Html5 data-src 属性将图像添加到您的网页中。您还可以使用常规 img 的 src 属性插入占位符。
<img data-src="1.jpg" src="Placeholder.jpg" alt="Image Alt"><img data-src="2.jpg" src="Placeholder.jpg" alt="Image Alt"><img data-src="3.jpg" src="Placeholder.jpg" alt="Image Alt">
3.Call the plugin on the img tags and specify the duration of the fadeIn effect as your images are come into view
3.调用 img 标签上的插件并在您的图像进入视图时指定淡入效果的持续时间
$('img').loadScroll(500); // in ms