html - 异步图像加载jquery

标签 html image css asynchronous

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

最佳答案

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

这是一个图像加载器,它预加载所有图像,然后调用 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/

相关文章:

Java编程帮助和android开发

javascript - 如何通过拖放重新排序 4 个 div(使用 angular2/4)?

image - 将文本添加到 .jpg/png/gif

javascript - 有人知道这里使用了什么 Javascript 库吗?

javascript - 在附加元素之前从 CSS 类获取宽度?

css - 在 php 中使用 css 时出现错误?

android - LeafletJS - 具有本地文件系统的缓存图 block

javascript - 将 html 文档中的 css 样式提取到外部 css 文件

jquery - 我无法在 Chrome 以外的任何其他程序中与 HTML map 交互?

css - GWT:为同一 CSS 字段返回多种样式