我有一个包含十几个大图像的页面:
<div id="gallery">
<img src="1.png" alt="" />
<img src="2.png" alt="" />
...
</div>
由于图像的大小,并行下载会在显示任何内容之前造成太长的延迟。
问题如何顺序加载图片,让2.png
只有在1.png
加载显示完毕后才开始加载?
我不想延迟加载(除非你知道一个插件总是加载图像,无论当前视口(viewport)如何)
<此解决方案:Loading images sequentially在最新的 Chrome、Firefox、IE 中对我不起作用。它将一次加载所有图像,然后显示它们
此答案中建议的插件 https://stackoverflow.com/a/25774333/525445有点功能,但它一次发出 2、3 个或有时更多的请求,所以没有做它应该做的事情
然后是这个插件,也在一些答案中提出:http://imagesloaded.desandro.com/不过,它还有其他用途 - 让您知道何时加载了所有图像,它做得很好。所以我试着像这样使用它:
var $gallery = $("#gallery");
$gallery.imagesLoaded(函数(){ $gallery.append(''); console.log("图片加载完毕"); }); $gallery.append('');
这里的想法是 - 在 imagesLoaded 事件中动态地一张一张地添加图像。但是,它仅针对第一张图像被触发(尽管它也是动态添加的),而第二张则不会。所以上面的代码导致两个图像都显示,但只有 1 个 console.log() 通知
任何建议表示赞赏。
最佳答案
基本上你想从一个空容器开始。图像的路径将包含在一个 Javascript 数组中,然后使用屏幕外元素加载方法一个接一个地导入。代码:
<div id="gallery"></div>
<script>
var images = [
{ src: '1.png', alt: 'I am the first image' },
{ src: '2.png', alt: 'Second image' }
];
function loadImageSequentially(imagesArray, appendTo, loadImageAtIndex) {
if (!loadImageAtIndex) loadImageAtIndex = 0; // assume first loading if not provided.
if (!imagesArray[loadImageAtIndex]) return;
var img = new Image();
// attach listeners first
img.onload = function() {
appendTo.appendChild(img);
loadImageSequentially(imagesArray, appendTo, loadImageAtIndex + 1);
}
img.onerror = function() {
// remove listeners
img.onload = img.onerror = null;
img.src = 'error.png'; // if you have a placeholder error png to display, put it here.
// life goes on...
appendTo.appendChild(img);
loadImageSequentially(imagesArray, appendTo, loadImageAtIndex + 1);
}
// assign attributes, which will start the loading.
img.src = imagesArray[loadImageAtIndex].src;
img.alt = imagesArray[loadImageAtIndex].alt;
}
// now run it.
var appendTo = document.getElementById('gallery')
loadImageSequentially(images, appendTo);
</script>
这个例子可以模块化并变得更好。但出于说明的目的,保留在此处。
关于javascript - 有没有办法(JavaScript 或 jQuery)顺序加载图像(防止并行下载),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30017448/