When using lazyload.js and swiper.js together, it is found that the loaded image does not load after adding it to one screen. I can't find the reason. I can use the following code. It is available for personal testing, and the mobile terminal and WeChat are normal.
var scrollElement = document.querySelector('.page'),
viewH = document.documentElement.clientHeight;
function lazyload() {
var nodes = document.querySelectorAll('img[data-src]');
Array.prototype.forEach.call(nodes, function (item, index) {
var rect;
if (item.dataset.src === '') return;
rect = item.getBoundingClientRect();
if (rect.bottom >= 0 && rect.top < viewH) {
(function (item) {
var img = new Image();
img.onload = function () {
item.src = img.src;
}
img.src = item.dataset.src;
item.dataset.src = '';
})(item)
}
})
}
function throttle(fun, delay, time) {
var timeout,
startTime = new Date();
return function () {
var context = this,
args = arguments,
curTime = new Date();
clearTimeout(timeout);
if (curTime - startTime >= time) {
fun.apply(context, args);
startTime = curTime;
} else {
timeout = setTimeout(fun, delay);
}
};
};
$(function () {
//动态加载元素时写在这里面更保险一些
lazyload();
//scrollElement为图片外面的父元素
scrollElement.addEventListener('scroll', throttle(lazyload, 500, 1000));
})