不加载隐藏图像

2024-05-25

我的网站上有一堆隐藏图像。它们的容器 DIV 具有 style="display: none"。根据用户的操作,某些图像可能会通过 JavaScript 显示。问题是我的所有图像都是在打开页面时加载的。我想通过仅加载最终可见的图像来减轻服务器的压力。我想知道是否有一种纯 CSS 方法可以做到这一点。这是我目前正在做的两种黑客/复杂的方法。正如您所看到的,这不是干净的代码。

<div id="hiddenDiv">
   <img src="spacer.gif" />
</div>

.reveal .img {
 background-image: url(flower.png);
}

$('hiddenDiv').addClassName('reveal');

这是方法2:

<img id="flower" fakeSrc="flower.png" />

function revealImage(id) {
 $('id').writeAttribute(
  'src',
  $('id').readAttribute('fakeSrc')
 );
}

revealImage('flower');

浏览器将加载任何具有src属性集,所以你要做的就是使用data-src在标记中并使用 JavaScript 来设置src属性,当你想要它加载时。

<img class="hidden" data-src="url/to/image.jpg" />

我创建了这个小插件来解决这个问题:

(function($){
    // Bind the function to global jQuery object.
    $.fn.reveal = function(){
        // Arguments is a variable which is available within all functions
        // and returns an object which holds the arguments passed.
        // It is not really an array, so by calling Array.prototype
        // he is actually casting it into an array.
        var args = Array.prototype.slice.call(arguments);

        // For each elements that matches the selector:
        return this.each(function(){
            // this is the dom element, so encapsulate the element with jQuery.
            var img = $(this),
                src = img.data("src");

            // If there is a data-src attribute, set the attribute
            // src to make load the image and bind an onload event.
            src && img.attr("src", src).load(function(){
                // Call the first argument passed (like fadeIn, slideIn, default is 'show').
                // This piece is like doing img.fadeIn(1000) but in a more dynamic way.
                img[args[0]||"show"].apply(img, args.splice(1));
            });
        });
    }
}(jQuery));

Execute .reveal在您要加载/显示的图像上:

$("img.hidden").reveal("fadeIn", 1000);

See jsFiddle 上的测试用例 http://jsfiddle.net/mekwall/PZy53/.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

不加载隐藏图像 的相关文章

随机推荐