我有一个页面,其中包含十几个大图像:
<div id="gallery">
<img src="1.png" alt="" />
<img src="2.png" alt="" />
...
</div>
由于图像的尺寸,并行下载导致太长延迟在显示任何内容之前。
问题:如何顺序加载图像,因此2.png
仅在 1.png
被满载并显示后才开始加载?
我不想要懒惰的加载(除非您知道一个插件,该插件将始终以同一顺序严格地图像,无论当前视口如何)
此解决方案:在最新的Chrome,Firefox,即,依次加载图像对我不起作用。它将一次加载所有图像,然后显示
此答案中建议的插件https://stackoverflow.com/a/25774333/525445在某种程度上有效,但它会立即提出2、3或更多请求,因此不应该做应该做的事情
然后有一个插件,在某些答案中也提出了:http://imagesloaded.desandro.com/它是为了其他东西 - 让您知道何时加载所有图像,都很好。所以我试图将其这样使用:
var $ gallery = $("#画廊");
$ GALLERY.IMAGESLOADED(function(){ $ GALLERY.APPEND(''); console.log("加载图像"); }); $ GALLERY.APPEND('');
这里的想法是 - 在上载事件上,动态添加图像。但是,它仅针对第一个图像触发(尽管也被动态添加),而第二张图像则没有。因此,以上代码会导致两个图像显示,但只有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>
这个示例可以模块化并改善。但以插图的目的为目的。
尝试在页面滚动上使用懒负载。当用户向其滚动时,它开始加载图像,因此图像没有加载,相反,它将以某种方式依次接近。