demo
思路:
为了让体验更好,如果页面一下要同时加载所有大量图片,会有白屏之类的体验,就懒加载。
- 判断图片有木有出现在页面,出现了,就加载它。
- 加不加载,靠控制img标签的src实现。
- 事件是窗口的滚动,这个窗口可以是window,父容器,分析得出。
- 加了定时器,只是为了让懒加载更生动点,实际不能南辕北辙。
- 可以加个函数节流,避免滚动导致的多次判断。
- 可以筛选已经加载过的图片,不让其进入再次判断的范围里。
代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>懒加载</title>
<style>
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
}
.box {
width: 100%;
}
.box img {
width: 50%;
height: 50%;
float: left;
}
.clearfix:after {
content: '';
display: block;
clear: both;
}
</style>
</head>
<body>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<div class="box clearfix">




















</div>
<script>
var isloading
$(window).on('scroll', function() {
var timer
clearTimeout(timer)
timer = setTimeout(start(), 200)
})
start()
function start() {
console.log($('.box img').not('[data-loaded]'))
$('.box img').not('[data-loaded]').each(function() {
var $node = $(this)
if (isshow($node)) {
setTimeout(loading($node), 2000)
}
})
}
function isshow($img) {
return $img.offset().top <= $(window).height() + $(window).scrollTop()
}
function loading($img) {
$img.attr('src', $img.attr('data-src'))
$img.attr('data-loaded', true)
}
</script>
</body>
</html>
网友评论