我不确定您为什么(或是否)要以特定顺序“加载”图像。请注意,浏览器很少打开单个连接。通常会收集所有资源(在下载 html 本身之后),浏览器将并行加载其中的许多资源。简而言之 - 如果您这样做是为了提高性能或速度,您会减慢整个过程!
一种更常见的延迟加载图像的方法是使用视口/滚动位置来决定应该“下一个”加载哪些图像,有一些 jquery 插件,例如lazyload.
无论如何 - 如果您不关心订单,并且您只想在准备好时进行特定于元素的回调,您可以执行以下操作:
$("img").one("load", function() {
var $this = this;
// 'this' is your specific element
// do whatever you like to do onready
}).each(function() {
// handle cached elements
if(this.complete) $(this).load();
});
如果您确实关心订单,并且您真的想在第一个图像准备好后加载下一个图像,您需要一种不同的方法。
首先:您的 HTML 不包含图像源,而是包含具有数据属性的图像:
<img data-src="the/path/to/your/image" data-assets-order="1" />
第二:在 JS 中,你收集所有这些没有真实来源的图像,你对集合进行排序,最后触发一个接一个的加载。
var toLoad = [];
// scanning for all images with a data-src attribute
// and collect them in a specified order.
$('img[data-src]').each(function() {
// either you define a custom order by a data-attribute (data-assets-order)
// or you use the DOM position as the index. Mixing both might be risky.
var index = $(this).attr('data-assets-order') ?
$(this).attr('data-assets-order') : toLoad.length;
// already existing? put the element to the end
if (toLoad[index]) { index = toLoad.length; }
toLoad[index] = this;
});
// this method handles the loading itself and triggers
// the next element of the collection to be loaded.
function loadAsset(index) {
if (toLoad[index]) {
var asset = $(toLoad[index]);
// bind onload to the element
asset.on("load", function() {
// in case it is ready, call the next asset
if (index < toLoad.length) {
loadAsset(index + 1);
}
});
// set the source attribut to trigger the load event
asset.attr('src', asset.attr('data-src'));
}
}
// we have assets? start loading process
if (toLoad.length) { loadAsset(index); }