[英]Disable loading images while the web-page is loading
我的大多数网站访问者使用有限的带宽和慢速的互联网。 因此,我正在尝试通过在加载网页时禁用加载图像和背景图像来减少加载时间并节省带宽,然后在单击“显示图像”按钮时提供加载网页图像的选项。
我正在考虑一些像延迟加载但点击动作的东西。
我感谢你的建议。
一个想法:
- 保留图像的空src属性
- 在一个属性上存储img urls(你可以称之为data-src)
- 当加载页面或用户点击“显示图像”时,使用Jquery将src替换为data-src值
我认为有两种不同的场景:
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类并循环遍历。
嵌套函数看起来有点令人讨厌,但这里是使用上面提到的方法解决问题的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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.