gpt4 book ai didi

html - 异步图像加载jquery

转载 作者:太空宇宙 更新时间:2023-11-04 12:21:53 26 4
gpt4 key购买 nike

是否可以在页面加载时异步加载图像?代码中的图像将在用户单击按钮时显示,这意味着它们不会立即显示。然后我问是否可以将图像加载到某种缓存中,以及何时需要使用它们而无需等待那么久就显示出来?

最佳答案

所有图像对象都由浏览器异步加载。

这是一个图像加载器,它预加载所有图像,然后调用 start() 方法。当调用 start() 时,所有图像都已完全加载并准备好显示:

// image loader

// put the paths to your images in imageURLs[]
var imageURLs=[];
imageURLs.push("myImage1.png");
imageURLs.push("myImage2.png");

// the loaded images will be placed in imgs[]
var imgs=[];

var imagesOK=0;
loadAllImages(start);

function loadAllImages(callback){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
callback();
}
};
img.onerror=function(){alert("image load failed");}
img.crossOrigin="anonymous";
img.src = imageURLs[i];
}
}

function start(){

// the imgs[] array now holds fully loaded images
// the imgs[] are in the same order as imageURLs[]

}

关于html - 异步图像加载jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28307794/

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