在加载网页时禁用加载图像

时间:2016-03-23 12:20:34

标签: javascript jquery lazy-loading

我的大多数网站访问者都使用有限的带宽&网速慢。 所以我试图通过禁用加载图像来减少加载时间并节省带宽。加载网页时的背景图像,然后在单击“显示图像”按钮时提供加载网页图像的选项。

我正在考虑一些像延迟加载但点击动作的事情。

感谢您的建议。

3 个答案:

答案 0 :(得分:1)

一个想法:

- 保留图像的空src属性

- 在一个属性上存储img url(你可以称之为data-src)

- 在加载页面或用户点击“显示图片”时,使用Jquery将src替换为data-src值

答案 1 :(得分:1)

我认为有两种不同的情况:

<强> IMG-代码

HTML:

<img src="" data-load="http://imagesource" alt="">

jQuery的:

$('img[data-load]').each(function(){        
  $(this).attr('src', $(this).data('load'));
});

<强>背景图像

HTML:

<div class="background-placeholder"></div>

CSS:

.background-placeholder {
  background-color:#fff;
  width:250px;
  height:250px;
}

.show-bg1 {
  background-image:url('http://imagesource');
}

jQuery的:

$('.background-placeholder').addClass('show-bg1');

未使用类时,CSS背景图像未加载(悬停时相同等) 这不是最有效的方法,但它可以让你知道它是如何完成的。 也许你可以在数据属性中存储带有正确背景图像的css类并循环遍历。

FIDDLE

答案 2 :(得分:0)

嵌套函数看起来有点令人讨厌,但是这里是使用上述方法解决问题的jQuery。

$(document).ready(function(){ // wait until the document is loaded
  $('#loadimages').click(function(){ // before registering the event handler 	
    $('img[data-src]').each(function(){ // and for each image with a data-src attribute    	
      $(this).attr('src', $(this).data('src')) // copy it's contents into the src attribute
    })
  })
})
img[data-src]{
  width: 200px;
  height: 400px;
  background: grey;
  position: relative;
}

img[data-src][src=""]::after {
  content: 'Placeholder';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, 50%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img src="" data-src="http://lorempixel.com/200/400"/> 
<img src="" data-src="http://lorempixel.com/200/400"/>
<img src="" data-src="http://lorempixel.com/200/400"/>
<button id="loadimages">Load Images</button>

相关问题