繁体   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