现如今富媒体信息时代,很多电商产品都会有大量的图片素材展示,无论是移动端、PC端都会可能遇到。如果一个展示页面有大量的图片需要加载,那么该如何进行优化?在这里,给大家整理一下我是怎么使用JS代码实现图片懒加载的。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="referrer" content="no-referrer"/>
<title>列表</title>
<script src="${staticUrl}/js/v5/jquery-1.7.2.min.js?v=${version}"></script>
</head>
<script>
//图片懒加载
function loadImg(url, obj){
if($(obj).attr("src") == '${imgUrl}/images/v5/noData.png'){
$(obj).attr("src", url)
}
}
//图片加载发生error, 替换效果
function onerrorLoadImg(obj){
var parent_ = $(obj).parent();
var temp = '<div class="noImg"><img src="${imgUrl}/images/v5/noData.png"><p>暂无图片</p></div>';
$(obj).remove();
parent_.append(temp);
}
</script>
<body class="page">
<div class="main">
<div class="list">
<div class="house">
<div class="house_list">
<ul>
<#list houseBoList as hb>
<li>
<a class="xq_pic" href="${cityUrl}/apartment/info?id=${hb.house.id}&defaultPic=${hb.showPic!}" target="_blank">
<!-- 图片做懒加载处理 -->
<#if hb.showPic??&&hb.showPic!=''>
<img src="${imgUrl}/images/v5/noData.png" onload="loadImg('${hb.showPic!}', this)" onerror="javascript:onerrorLoadImg(this);">
<#else>
<div class="noImg">
<img src="${imgUrl}/images/v5/noData.png"><p>暂无图片</p>
</div>
</#if>
</a>
</li>
</#list>
</ul>
</div>
</div>
</div>
</div>
</body>
</html>
关键技术点:
需要用好img标签的onload 、onerror两个属性!
特别提示:
onerror使用的过程中可能会出现死循环,大家切记需要获取当前this对象的父对象,然后进行remove操作。
以上代码仅供参考,如有不当之处,欢迎指出!!!
更多干货,欢迎大家关注我。期待和大家一起更好的交流、探讨技术!!!