JavaScript瀑布流图片懒加载实现方案
作者:半夏时间:2026-10-29 22:18:11浏览:229
本文介绍基于JavaScript的瀑布流图片懒加载实现方法。通过监听窗口滚动事件,动态计算图片位置与可视区域高度,仅在图片进入视口时加载资源。示例代码兼容Zepto.js与jQuery,适用于移动端及PC端网页优化,有效提升页面加载性能。
JavaScript瀑布流图片懒加载实现方案
近期项目中应用了懒加载技术,目前进展顺利。由于开发重点偏向移动端,代码库选用的是zepto.js,但该方案同样兼容jQuery,可无缝切换使用。
具体实现代码如下所示:
/**
* Created by zhiqiang on 2015/10/14.
* hpuhouzhiqiang@gmail.com
* 图片的懒加载
**/
function loadImgLazy(node) {
var lazyNode = $('[node-type=imglazy]', node),
mobileHeight, lazyOffSetHeight, tempHeight, currentNodeTop, imgObject,
imgDataSrc, localUrl;
localUrl = location.href;
// 获取当前浏览器可视区域的高度
mobileHeight = $(window).height();
return function(co) {
var conf = {
'loadfirst': true,
'loadimg': true
};
for (var item in conf) {
if (item in co) {
conf[item] = co[item];
}
}
var that = {};
var _this = {};
/**
* [replaceImgSrc 动态替换节点中的src]
* @param {[type]} tempObject [description]
* @return {[type]} [description]
*/
_this.replaceImgSrc = function(tempObject) {
var srcValue;
$.each(tempObject, function(i, item) {
imgObject = $(item).find('img[data-lazysrc]');
imgObject.each(function(i) {
imgDataSrc = $(this).attr('data-lazysrc');
srcValue = $(this).attr('src');
if (srcValue == '#') {
if (imgDataSrc) {
$(this).attr('src', imgDataSrc);
$(this).removeAttr('data-lazysrc');
}
}
});
});
};
/**
* 首屏判断屏幕上是否出现imglazy节点,有的话就加载图片
* @param {[type]} i) { currentNodeTop [description]
* @return {[type]} [description]
*/
_this.loadFirstScreen = function() {
if (conf.loadfirst) {
lazyNode.each(function(i) {
currentNodeTop = $(this).offset().top;
if (currentNodeTop < mobileHeight + 800) {
_this.replaceImgSrc($(this));
}
});
}
};
//当加载过首屏以后按照队列加载图片
_this.loadImg = function() {
if (conf.loadimg) {
$(window).on('scroll', function() {
var imgLazyList = $('[node-type=imglazy]', node);
for (var i = 0; i < 5; i++) {
_this.replaceImgSrc(imgLazyList.eq(i));
}
});
}
};
that = {
replaceImgSrc: _this.replaceImgSrc(),
mobileHeight: mobileHeight,
objIsEmpty: function(obj) {
for (var item in obj) {
return false;
}
return true;
},
destory: function() {
if (_this) {
$.each(_this, function(i, item) {
if (item && item.destory) {
item.destory();
}
});
_this = null;
}
$(window).off('scroll');
}
};
return that;
};
}
希望上述内容能为读者学习JavaScript图片懒加载技术提供有价值的参考。
作者最新文章
JavaScript闭包与类(Class)的区别及适用场景对比
2026-11-05 15:48:57
JavaScript入门要学ES6吗?let与箭头函数等新特性解析
2026-11-05 14:49:16
JavaScript 8种数据类型详解:基本类型与引用类型的区别
2026-11-05 14:25:15
怎么在JavaScript中使用async/await优化Ajax异步流程
2026-11-05 13:56:15
JavaScript replace回调函数实现动态正则替换逻辑
2026-11-05 13:52:13
