JS/CSS:从HTML文件中预加载隐藏的图像

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

本文关键字:加载 隐藏 图像 文件 CSS HTML JS      更新时间:2023-09-26

让我们假设我的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隐藏它们。准备好了,这不会阻止它们在某些浏览器中加载吗?如果我让它们保持可见,一些图像可能会在它们全部加载之前出现,这是不希望看到的。我不想用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;
}

并在preload.

中添加images' 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/