gpt4 book ai didi

javascript - 如何防止显示部分加载的图像?

转载 作者:行者123 更新时间:2023-11-30 07:54:34 35 4
gpt4 key购买 nike

如果您在 img 标签中有 3MB 的图像,则加载需要几秒钟。加载图像时,浏览器有点“打印”它 - 它首先显示顶部,然后是中间,然后是底部。我如何防止这种情况发生?我宁愿隐藏图像并在一两秒钟后显示 - 当它完全加载时。

最佳答案

一种方法是给他们一个类,给他们 opacity: 0 所以他们不显示:

<img src="/path/to/image" class="loading">

在 CSS 中:

.loading {
opacity: 0;
}

head 中,如果 JavaScript 被禁用,我们会覆盖它(因此我们对非 JavaScript 访问者并不不友好):

<noscript>
<style>
.loading {
opacity: 1;
}
</style>
</noscript>

...然后在页面底部的代码中,找到所有图像并在加载后删除类,然后...(参见评论):

(function() {
// Get an array of the images
var images = Array.prototype.slice.call(document.querySelectorAll("img.loading"));
// Hook their load and error events, even though they may have already fired
images.forEach(function(image) {
image.addEventListener("load", imageDone.bind(null, image));
image.addEventListener("error", imageDone.bind(null, image)); // Could handle errors differently
});
// Check to see if any images are already complete
checkImages();

function imageDone(img) {
img.classList.loading("remove");
images = images.filter(function(entry) { entry != img });
}
function checkImages() {
images.forEach(function(image) {
if (image.complete) {
imageDone(image);
}
});
if (images.length) {
// Check back in a second
setTimeout(checkImages, 1000);
}
}
})();

这是一种万全之策。它会主动检查图像是否已完成加载,还会被动地处理图像的 loaderror 事件。理论上,我们不需要 setTimeout,您可以在没有它的情况下进行测试,但是...

请注意,一旦图像完成,我们如何删除类以使其可见。

关于javascript - 如何防止显示部分加载的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43428201/

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