簡體   English   中英

異步圖像加載jQuery

[英]asynchronous image loading jquery

頁面加載時是否可以異步加載圖像? 當用戶單擊按鈕時,將顯示代碼中的圖像,這意味着它們不會立即顯示。 然后,我問是否有可能將圖像加載到某種緩存中,何時需要使用它們而無需等待那么長時間就可以顯示它們?

所有圖像對象均由瀏覽器異步加載。

這是一個圖像加載器,它會預加載所有圖像,然后調用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[]

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM