javascript 延迟加载图片
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5582739/
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
Lazy loading images
提问by Nick Clark
I'm looking for a JQuery plugin that supports lazy loading images. The Lazy Load JQuery pluginis no longer supported and does not work in Firefox.
我正在寻找支持延迟加载图像的 JQuery 插件。该延迟加载jQuery插件不再支持,并不会在Firefox的工作。
Does anyone know a good alternative that supports most modern browsers?
有谁知道支持大多数现代浏览器的好选择?
I'm also open to other approaches. I have a hidden div with images that I don't want to load unless the div is made visible. Let me know if there are better approaches to deferring the image load in this situation.
我也对其他方法持开放态度。我有一个隐藏的 div,里面有我不想加载的图像,除非 div 可见。让我知道在这种情况下是否有更好的方法来推迟图像加载。
回答by Jon z
I encountered a similar situation in a tab style page where the content in initially invisible tabs was downloading unnecessarily. The solution I went with was to create markup like:
我在选项卡样式页面中遇到了类似的情况,其中最初不可见的选项卡中的内容被不必要地下载。我采用的解决方案是创建如下标记:
<img src="#" data-src="/img/foo.png"/>
and then in the javascript that handles the tab transitions I also substituted the "data-src" attribute into the "src" attribute of those images.
然后在处理选项卡转换的 javascript 中,我还将“data-src”属性替换为这些图像的“src”属性。
$thisTab.find('img[data-src]').each(function(img) {
var $img = $(img);
$img.attr('src', $img.attr('data-src'))
.removeAttr('data-src');
});
This accomplishes the goal of only loading the images when the tab is selected, and is valid html5!
这实现了仅在选择选项卡时加载图像的目标,并且是有效的 html5!
回答by John
I was having an issue with it not working in FF as well, but I got it working when I filled out the initial src attribute value with an image, like Monsieur Tuupola does on this example page, where he uses a 1px x 1px gray gif image for a place holder:
我遇到了一个问题,它也不能在 FF 中工作,但是当我用图像填写初始 src 属性值时,我让它工作了,就像图乌波拉先生在这个示例页面上所做的那样,他使用了 1px x 1px 灰色 gif占位符的图像:
http://www.appelsiini.net/projects/lazyload/enabled_gazillion.html
http://www.appelsiini.net/projects/lazyload/enabled_gazillion.html
Fire 'er up in FF, and it'll work.
在 FF 中启动,它会起作用。
回答by Calum
I know the dev says it's not working but I'm using LazyLoad on a project right now and it works fine in FF (I'm using Firefox 4). It takes about 24seconds to download and set up so give it a go to see if it works for you :)
我知道开发人员说它不起作用,但我现在正在一个项目上使用 LazyLoad,它在 FF 中运行良好(我使用的是 Firefox 4)。下载和设置大约需要 24 秒,所以试试看它是否适合你:)
回答by Kishor Parida
Found this solution here
在这里找到了这个解决方案
<h1>List of 10 alberts</h1>
<div class="albert_container"></div>
<div class="loading_albert" style="display:none;"><span>Loading ....</span></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
var req = '';
$(window).scroll(function () {
console.log(req);
if (req === 'sent') {
return false;
}
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
req = 'sent';
showLoader();
setTimeout(function () {
fetchAlberts();
}, 1000);
}
});
function fetchAlberts() {
var html = '';
$.get("/ByKishor/data.php").done(function (response) {
var data = JSON.parse(response);
for (var i in data) {
html += "<div class='albert_child'><b>" + i + "</b> : " + data[i].name + "</div>";
}
$(".albert_container").append(html);
req = '';
hideLoader();
});
}
function showLoader() {
$(".loading_albert").show();
}
function hideLoader() {
$(".loading_albert").hide();
}
fetchAlberts();
});
</script>
回答by agaase
There is a good lightweight jquery plugin - imgr. Check here https://github.com/agaase/imgr.
有一个很好的轻量级 jquery 插件 - imgr。在这里查看https://github.com/agaase/imgr。
It has following main features -
它有以下主要特点——
- Its mobile optimised; so it should work on mobile browsers too.
- It supports normal image elements and elements with background images.
- You can either do a lazy load of images as you scroll or the normal way of loading all once the page is loaded.
- 它的移动优化;所以它也应该适用于移动浏览器。
- 它支持普通图像元素和带有背景图像的元素。
- 您可以在滚动时延迟加载图像,也可以在加载页面后以正常方式加载所有图像。
回答by Hyman Giffin
I am pretty certain that Javascript is a bit overkill and a wee bit backwards (especially if using jQuery without the defer=""
attribute on the script) since it does take time for the javascript to get parsed and executed. Instead, use the decoding
attributeset to async like so.
我很确定 Javascript 有点矫枉过正,而且有点倒退(特别是如果使用 jQuery 而没有defer=""
脚本上的属性),因为解析和执行 javascript 确实需要时间。相反,像这样使用设置为 async的decoding
属性。
<img src="/path/to/file.jpg" decoding="async"></img>
Also, I am assuming that the most likely reason for why you want to lazyload images is to make your website load faster. If this is the case, then you can make your website load a huge amount even faster simply by converting your images to jpegs and compressing them with compressor.io/JPEGmini(upload your jpeg file to both and use whichever turns out smaller after compression).
此外,我假设您想要延迟加载图像的最可能原因是使您的网站加载速度更快。如果是这种情况,那么您可以通过将图像转换为jpeg 并使用compressor.io/ JPEGmini压缩它们(将您的 jpeg 文件上传到两者并使用压缩后较小的那个)来使您的网站加载速度更快。.
Next, while full support in all browsers is not there yet, more and more browsers are starting to support it. I for one prefer to take the practical approach of making my websites full of the fast new features, and taking a backseat while my website grows faster with more supporting browsers, instead of spending vast amounts of time making my website load fast on old outdated browsers just to accommodate a small percentage of my users who really should update their browser more often.
其次,虽然还没有在所有浏览器中得到完全支持,但越来越多的浏览器开始支持它。我更喜欢采取实用的方法让我的网站充满快速的新功能,并在我的网站通过更多支持的浏览器增长得更快时退居二线,而不是花费大量时间让我的网站在旧的过时浏览器上快速加载只是为了容纳一小部分真正应该更频繁地更新浏览器的用户。
回答by eisbehr
I've just created an example, using jQuery.Lazy, to solve this problem in another way, and then saw that these question was a bit older. ;)
我刚刚创建了一个例子,使用jQuery.Lazy,以另一种方式解决这个问题,然后看到这些问题有点老了。;)
But nevermind, now I would like to show you my solution, even for possible other who want to do something like this.
但是没关系,现在我想向您展示我的解决方案,即使对于其他想要做这样的事情的人也是如此。
This example looks big on the first view, but it is mostly the creation of the example structure. The most interessting line is the .update()
call on the plugin.
这个示例在第一个视图上看起来很大,但它主要是示例结构的创建。最有趣的一行是.update()
对插件的调用。
lazy.update();
After a tab change we force the plugin to update the view by this line. Everything else is managed automatically. Pretty easy imo.
在选项卡更改后,我们强制插件通过此行更新视图。其他一切都是自动管理的。很容易imo。
The working example can be found below. If you like to play with it, I created a jsFiddletoo.
可以在下面找到工作示例。如果你喜欢玩它,我也创建了一个jsFiddle。
// create a lazy instance
var lazy = $("img").lazy({
chainable: false,
visibleOnly: true,
appendScroll: $("#content div"),
// below config is just for demo purpose
threshold: 0,
afterLoad: function(e) {
var image = e.attr("src").match(/tab\+(.*)\: image (\d)/g)[0];
console.log(image.replace("+", " ").replace("%20", " "));
}
});
// your tab controller
$("#header li").click(function() {
$("#content div").hide().eq($(this).index()).show();
// update lazy instance after tab change manually
lazy.update();
});
html * {
margin: 0;
padding: 0;
}
ul#header {
list-style: none;
margin: 10px 10px 0;
}
ul#header li {
display: inline-block;
background: #000;
color: #fff;
padding: 4px 10px;
margin-right: 10px;
}
ul#header li:hover {
cursor: pointer;
color: #f00;
}
div#content div {
display: none;
width: 520px;
height: 350px;
overflow: auto;
background: #ccc;
padding: 10px;
border: 1px solid #000;
margin-left: 10px;
}
div#content div img {
width: 500px;
height: 200px;
margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.lazy/1.7.3/jquery.lazy.min.js"></script>
<ul id="header">
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
<div id="content">
<div style="display: block;">
<img data-src="//dummyimage.com/500x200/000/ffffff&text=tab+one: image 1" />
<img data-src="//dummyimage.com/500x200/000/ffffff&text=tab+one: image 2" />
<img data-src="//dummyimage.com/500x200/000/ffffff&text=tab+one: image 3" />
<img data-src="//dummyimage.com/500x200/000/ffffff&text=tab+one: image 4" />
<img data-src="//dummyimage.com/500x200/000/ffffff&text=tab+one: image 5" />
</div>
<div>
<img data-src="//dummyimage.com/500x200/000/ffffff&text=tab+two: image 1" />
<img data-src="//dummyimage.com/500x200/000/ffffff&text=tab+two: image 2" />
<img data-src="//dummyimage.com/500x200/000/ffffff&text=tab+two: image 3" />
<img data-src="//dummyimage.com/500x200/000/ffffff&text=tab+two: image 4" />
<img data-src="//dummyimage.com/500x200/000/ffffff&text=tab+two: image 5" />
</div>
<div>
<img data-src="//dummyimage.com/500x200/000/ffffff&text=tab+three: image 1" />
<img data-src="//dummyimage.com/500x200/000/ffffff&text=tab+three: image 2" />
<img data-src="//dummyimage.com/500x200/000/ffffff&text=tab+three: image 3" />
<img data-src="//dummyimage.com/500x200/000/ffffff&text=tab+three: image 4" />
<img data-src="//dummyimage.com/500x200/000/ffffff&text=tab+three: image 5" />
</div>
</div>
回答by Медведев Александр
<img src="#" data-src="/img/foo.png"/>
.........................................................................
$('img[data-src]').each(function() {
$(this).attr('src', $(this).attr('data-src')).removeAttr('data-src');
});