簡體   English   中英

JS / CSS:隱藏HTML文件時預加載圖像

[英]JS/CSS: Preload images from the HTML file while they are hidden

假設我的html文檔中有幾個img標記,所有這些標記都應該以幻燈片形式顯示,一次顯示一個圖像。

<div id="gallery">
    <img class="slide" src="images/1.png" width="600" height="400" alt=""/>
    <img class="slide" src="images/2.png" width="600" height="400" alt=""/>
    <img class="slide" src="images/3.png" width="600" height="400" alt=""/>
    <img class="slide" src="images/4.png" width="600" height="400" alt=""/>
</div>

我不希望顯示這些圖像,直到它們被加載全部並且一旦加載所有我想將它們呈現為幻燈片放映(該部分並不重要)。

我無法真正理解它是如何工作的是在隱藏時加載圖像。 讓我們假設我將它們全部隱藏起來display:none在$ .ready之后display:none ,這會不會阻止它們在某些瀏覽器中加載嗎? 如果我讓它們可見,則在加載所有圖像之前可能會出現一些圖像,這是不合需要的。 我不想使用ajax加載它們。

我再一次嘗試做什么:

  • 將圖像放在html中,而不是用ajax加載它們

  • 在加載所有這些之前不要顯示它們

一些建議如何實現這一目標? 我對加載所有內容時如何顯示它們不感興趣,我對如何在加載時隱藏它們以及它們仍然會加載感興趣。 謝謝!

首先,您需要確保最初沒有顯示任何圖像。 為此,您需要更改樣式表。

請注意,只是因為CSS設置為display: none並不意味着瀏覽器不會加載它。 瀏覽器仍然加載圖像,它根本不顯示它。

你在樣式表中在這種情況下做了什么:

/* prevent images from being displayed before they are loaded ready */
#gallery img {
    display: none;
}

然后,使用一些jQuery,在完全加載時顯示圖像:

jQuery(function($) {
    $('#gallery img').load(
        function() {
            $(this).show();
        }
    );
});

這將顯示加載時的每個圖像。

要么
如果你想等到所有這些都被加載,你的jQuery會有點不同:

jQuery(function($) {
    // Get count of images
    var icount = $('#gallery img').length;
    // Initialize count to track loaded images
    var lcount = 0;
    $('#gallery img').load(
        function() {
             // If the loaded images is equal to the total images, show them all
             if (++lcount >= icount) {
                 $('#gallery img').show();
             }
        }
    );
});

要么
最后,如果你只是想在顯示它們之前等到整個頁面被加載,那么使用這個jQuery:

jQuery(window).load(function($) {
    $('#gallery img').show();
});

確保圖像加載並且不會出現任何問題的最佳簡單解決方案是:

.preload{
    position: absolute;
    top: -9999px;
    left: -9999px;
}

並在預加載中添加圖像'html的副本。

加載那些在JavaScript中

(function(){
    imgURLs = ['a.jpg', 'b.jpg', 'c.jpg', 'd.jpg'];
    imgs = [];
    var i = 0,
        len = imgURLs.length;
    loadAsset();

    function loadAsset(){
        if (i < len){

            imgs[i] = new Image();
            imgs[i].src = imgURLs[i];
            imgs[i].onload = function(){
                i++;
                loadAsset();
            }
        } else {
            //some init function for the slideshow
            initSlideShow();
        }
    }
})();

您可以使用jQuery“Deferred”對象加載圖像,也稱為promise。

var promises = [];
$('#gallery .slide').each(function(){
    var promise = $.Deferred();
    $(this).load(function(){ promise.resolve();} );
    promises.push(promise);
});
$.when.apply($,promises).then(function(){
    $('#gallery .slide').show();
});

http://api.jquery.com/category/deferred-object/

暫無
暫無

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

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