图片懒加载
手写js
var $window = $(window);
var onScroll = function () {
$img=$('img[data-src]')
var wtop = $window.scrollTop();
if ($img.length > 0) {
var wheight = $window.height();
var loadedIndex = [];
$.each($img, function (index,el) {
let self = $(el)
if (self.offset().top - wtop < wheight) {
self.attr('src', self.attr('data-src'));
loadedIndex.unshift(index);
}
});
$.each(loadedIndex, function (index) {
$img.splice(index, 1);
});
}
};
$window.scroll(onScroll);
onScroll();
引入lazyload.js
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lazyload@2.0.0-rc.2/lazyload.js"></script>
</head>
<body>
<img data-src="" alt="">
</body>
</html>
<script>
lazyload($('img[data-src]'));
</script>
参数查看