图片延迟加载

来源:互联网 发布:ubuntu终端打不开 编辑:程序博客网 时间:2024/05/14 21:12
 
<script type="text/javascript">Array.prototype.remove = function(dx){if (!isNaN(dx) && dx < this.length) {// 数组新的长度-1var newLength = this.length - 1;// 从删除索引部分开始遍历集合(可减少遍历次数),依次进1for ( var i = dx; i < newLength;) {this[i] = this[++i]}// 设置新的长度this.length = newLength;}}{// 窗口滚动条滚动时,可视区域发生改变,调用延迟加载图片的方法window.onscroll = function() {var scrollTop = document.compatMode == "CSS1Compat" ? document.documentElement.scrollTop: document.body.scrollTop;var clientHeight = document.documentElement.clientHeight;// alert(sTop+"--"+cHeight);lazyLoadImgesMethod();};// 窗口大小改变时,可视区域改变,调用延迟加载图片的方法window.onresize = function() {lazyLoadImgesMethod();};// 需要延迟加载的图片元素集合lazyLoadImgArray = document.getElementsByName("lazy_load_img");// 为了便于使用remove方法,创建新的array存储这些image对象lazyLoadImgArrayTmp = null;if (lazyLoadImgArray != null && lazyLoadImgArray.length > 0) {lazyLoadImgArrayTmp = new Array();for (i = 0; i < lazyLoadImgArray.length; i++) {lazyLoadImgArrayTmp[i] = lazyLoadImgArray[i];}}lazyLoadImgesMethod = function() {// 兼容各浏览器的clientWidth,clientHeight,scrollWidth,scrollHeight,scrollLeft,scrollTopvar cWidth, cHeight, sWidth, sHeight, sLeft, sTop;if (document.compatMode == "BackCompat") {cWidth = document.body.clientWidth;cHeight = document.body.clientHeight;sWidth = document.body.scrollWidth;sHeight = document.body.scrollHeight;sLeft = document.body.scrollLeft;sTop = document.body.scrollTop;} else // document.compatMode == "CSS1Compat"{cWidth = document.documentElement.clientWidth;cHeight = document.documentElement.clientHeight;sWidth = document.documentElement.scrollWidth;sHeight = document.documentElement.scrollHeight;sLeft = document.documentElement.scrollLeft == 0 ? document.body.scrollLeft: document.documentElement.scrollLeft;sTop = document.documentElement.scrollTop == 0 ? document.body.scrollTop: document.documentElement.scrollTop;}if (lazyLoadImgArrayTmp != null && lazyLoadImgArrayTmp.length > 0) {// 遍历所有延迟加载的图片for (i = 0; i < lazyLoadImgArrayTmp.length; i++) {// 计算该元素与顶部距离objTopDistance = getTopDistance(lazyLoadImgArrayTmp[i]);// 计算当前可视区域至顶部的距离bodyTopDistance = sTop + cHeight;// 如果该元素在可视区域范围或可视范围之上,加载当前元素图片(可以调整上下相差的数值,改变加载的位置)if (bodyTopDistance > objTopDistance&&objTopDistance+205>sTop) {// 设置样式显示lazyLoadImgArrayTmp[i].style.visibility = "visible";// 加载src_lazy属性下的图片lazyLoadImgArrayTmp[i].src = lazyLoadImgArrayTmp[i].getAttribute("src_lazy");// 移除该数据,不需要再次加载lazyLoadImgArrayTmp.remove(i--);}}} else {// 已经全部加载完毕停止事件触发window.onscroll = null;window.onresize = null;}};/** * 获取对象到顶部的距离数值 *  * @param elementObj:页面元素对象 * @return 获取参数对象距页面顶部的距离(px) */function getTopDistance(elementObj) {// 元素相对顶部距离topDistance = null;if (elementObj) {topDistance = 0;do {// 循环累加元素相对上级元素的距离,直到再无上级,即为总距离topDistance += elementObj.offsetTop;elementObj = elementObj.offsetParent} while (elementObj != null);}return topDistance;}/*if (document.body.scrollTop == 0) {// 第一次加载,加载当前区域lazyLoadImgesMethod();}*/}</script>