javascript Waterfall streaming image lazy load instance
- 2021-01-03 20:49:10
- OfStack
Lazy loading has been used in recent projects, but update 1 is now common, since zepto.js is usually used for mobile development. It can also be used with jQuery.
The code is as follows:
/**
* Created by zhiqiang on 2015/10/14.
* hpuhouzhiqiang@gmail.com
* Lazy loading of pictures
**/
function loadImgLazy(node) {
var lazyNode = $('[node-type=imglazy]', node),
mobileHeight, lazyOffSetHeight, tempHeight, currentNodeTop, imgObject,
imgDataSrc, localUrl;
localUrl = location.href;
// Gets the height of the current browser's visual area
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 Dynamic replacement in nodes 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');
}
}
});
});
};
/**
* The first screen determines whether it appears on the screen imglazy Nodes, if any, load images
* @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));
}
});
}
};
// When the first screen is loaded, load the image as a queue
_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;
};
}
I hope this article is helpful for you to learn the lazy loading of javascript images.