gpt4 book ai didi

javascript - 知道特定资源何时完成加载

转载 作者:行者123 更新时间:2023-12-02 13:46:00 25 4
gpt4 key购买 nike

很抱歉,如果该线程被重复,但我在浏览器中没有找到它。

我想创建/处理一个事件,让我知道特定资源何时加载到网页中。 (类似于 onload 或 DOMContentLoaded,但我需要知道每个资源何时完成,而不是整个页面)示例--> Assets = image1,image2,image3,...

当完成加载image1时触发ready事件,

就绪事件触发后开始加载图像2

继续...继续...

在最后一张图像之后,再次触发就绪事件。

最终结果与 DOMContentLoaded 或“windows.onload”相同,但正如我所说,我无法在 Assets 加载中间放置一些逻辑。

有人知道如何处理这种事情吗?

最佳答案

我不确定为什么(或者是否)您想以特定顺序“加载”图像。请注意,浏览器很少打开单个连接。通常,所有资源都会被收集(在下载 html 本身之后),并且浏览器将并行加载其中的许多资源。简而言之 - 如果您这样做是为了性能或速度,您会减慢该过程!

延迟加载图像的更常见方法是使用视口(viewport)/滚动位置来决定“下一个”应该加载哪些图像,有一些 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); }

关于javascript - 知道特定资源何时完成加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41394832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com