不要加载隐藏的图像 [英] Don't load hidden images

查看:133
本文介绍了不要加载隐藏的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站上有一堆隐藏的图片。他们的容器DIV有style =display:none。根据用户的操作,一些图像可能通过javascript显示。问题是,所有我的图像加载打开页面。我想通过只加载最终变得可见的图像,减少服务器上的压力。我想知道是否有一个纯CSS的方式来做到这一点。这里是我目前做的两个hacky /复杂的方式。正如你所看到的,它不是干净的代码。

I have a bunch of hidden images on my website. Their container DIVs have style="display: none". Depending on the user's actions, some images may be revealed via javascript. The problem is that all my images are loaded upon opening the page. I would like to put less strain on the server by only loading images that eventually become visible. I was wondering if there was a pure CSS way to do this. Here are two hacky/complicated ways I am currently doing it. As you can see, it's not clean code.

<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');


推荐答案

这里有一个jQuery解决方案:

Here's a jQuery solution:

$(function () {
   $("img").not(":visible").each(function () {
       $(this).data("src", this.src);
       this.src = "";
   });

   var reveal = function (selector) {
       var img = $(selector);
       img[0].src = img.data("src");
   }
});

它类似于你的解决方案,除了它不使用 fakeSrc 属性。它清除 src 属性以阻止其加载并将其存储在其他位置。一旦你准备好显示图像,你使用显示功能很像你在你的解决方案。如果你不使用jQuery,我的道歉,但该过程应该可以转移到你使用的任何框架(如果有)。

It's similar to your solution, except it doesn't use the fakeSrc attribute in the markup. It clears the src attribute to stop it from loading and stores it elsewhere. Once you are ready to show the image, you use the reveal function much like you do in your solution. I apologize if you do not use jQuery, but the process should be transferable to whichever framework (if any) that you use.

注意:这段代码特别必须运行之前该窗口已触发加载事件,但在DOM加载后。

Note: This code specifically must be ran before the window has fired the load event but after the DOM has been loaded.

这篇关于不要加载隐藏的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆