javascript JQuery在显示前加载div内的所有图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12810878/
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
JQuery Load all images inside div before display
提问by AJ Naidas
I want to load every image inside a div before actually displaying them. I have something similar to this:
我想在实际显示它们之前加载 div 中的每个图像。我有类似的东西:
<div>
<img src="1.jpg" />
<img src="1.jpg" />
<img src="1.jpg" />
<img src="1.jpg" />
<img src="1.jpg" />
<img src="1.jpg" />
</div>
At first I tried doing things like:
起初我尝试做这样的事情:
$('div img').load(function() {
$('div img').show();
});
Or this:
或这个:
$('div').find('img').load(function() {
$('div img').show();
});
Unfortunately, this didn't work because once the browser loads even just a single image, it fires the event. Any ideas on how to load everything first ? Thanks!
不幸的是,这不起作用,因为一旦浏览器加载了单个图像,它就会触发该事件。关于如何首先加载所有内容的任何想法?谢谢!
回答by nathan
You can keep track of how many images have loaded:
您可以跟踪已加载的图像数量:
var $images = $('div img'),
preloaded = 0,
total = $images.length;
$images.load(function() {
if (++preloaded === total) {
// Done!
}
});
回答by Fresheyeball
Unfortunately there is not easy way to do this in a cross browser compatible way. But luckily there are 2 plugins out there that can make it painless.
不幸的是,没有简单的方法可以跨浏览器兼容的方式来做到这一点。但幸运的是,有 2 个插件可以让它变得轻松。
Check out waitforimagesand imagesloaded
Then you can do:
然后你可以这样做:
$('div').waitForImages(function(){
$(this).find('img').show();
});
回答by Tariqulazam
回答by LogPi
First, The modern browser can execute concurrently 6 request => Don't load so many image at the load time. If you have many images, you can set the images at the back 'src=""' or non set "src" attributes, And set after the first images loaded
首先,现代浏览器可以并发执行 6 个请求 => 加载时不要加载这么多图像。如果你有很多图片,你可以在后面的图片设置 'src=""' 或不设置 "src" 属性,并在第一张图片加载后设置
Second, You can check "image was loaded" by using
其次,您可以使用检查“图像已加载”
document.getElementById('#imageId').complete == !0
You can check with image with the largest size or the last image in DOM to make sure the others images were loaded.
您可以检查最大尺寸的图像或 DOM 中的最后一个图像,以确保其他图像已加载。
Hope it 'll help you.
希望它会帮助你。
回答by Reft
This worked for me:
这对我有用:
$(document).ready(function () {
$('#div with images').hide();
});
$(window).load(function () {
$('#div with images').show();
});