懒加载:假如一个网站需要有大量的图片,如果一开始全部加载的话用户刚进入页面的时候需要较久的时间才能进入,这时候就可以使用懒加载的方式,懒加载就是一开始不全部加载图片,当用户浏览到哪里的时候再加载哪里的图片
为了缓解浏览器的压力,提高用户体验
一开始所有的图片指向默认的图片,实际只发送一次请求
把图片地址放到一个新增的自定义元素data-src
中
出现在视窗后加载
怎么判断是否滚动到当前窗口?为了测试,在最后一栏添加了h1
<div class="wrap">
<div class="images clearfix">
<img src="https://tse1-mm.cn.bing.net/th?id=OGC.1ac64a61ff1e93c2c3f0754507f6c8aa&pid=1.7&rurl=http%3a%2f%2fimg.lanrentuku.com%2fimg%2fallimg%2f1609%2f5-160914192R6.gif&ehk=8UCm1CrQWYyZ1qMxfhVsHw" class="image" data-src="http://img15.3lian.com/2015/f2/160/d/73.jpg">
<img src="https://tse1-mm.cn.bing.net/th?id=OGC.1ac64a61ff1e93c2c3f0754507f6c8aa&pid=1.7&rurl=http%3a%2f%2fimg.lanrentuku.com%2fimg%2fallimg%2f1609%2f5-160914192R6.gif&ehk=8UCm1CrQWYyZ1qMxfhVsHw" class="image" data-src="https://tse1.mm.bing.net/th?id=OIP.rsK6_G2dC5YMPBtRm3rasgHaEo&pid=Api">
<img src="https://tse1-mm.cn.bing.net/th?id=OGC.1ac64a61ff1e93c2c3f0754507f6c8aa&pid=1.7&rurl=http%3a%2f%2fimg.lanrentuku.com%2fimg%2fallimg%2f1609%2f5-160914192R6.gif&ehk=8UCm1CrQWYyZ1qMxfhVsHw" class="image" data-src="http://img15.3lian.com/2015/f2/160/d/75.jpg">
<img src="https://tse1-mm.cn.bing.net/th?id=OGC.1ac64a61ff1e93c2c3f0754507f6c8aa&pid=1.7&rurl=http%3a%2f%2fimg.lanrentuku.com%2fimg%2fallimg%2f1609%2f5-160914192R6.gif&ehk=8UCm1CrQWYyZ1qMxfhVsHw" class="image" data-src="http://img8.zol.com.cn/bbs/upload/13665/13664158.jpg">
<img src="https://tse1-mm.cn.bing.net/th?id=OGC.1ac64a61ff1e93c2c3f0754507f6c8aa&pid=1.7&rurl=http%3a%2f%2fimg.lanrentuku.com%2fimg%2fallimg%2f1609%2f5-160914192R6.gif&ehk=8UCm1CrQWYyZ1qMxfhVsHw" class="image" data-src="http://img15.3lian.com/2015/f2/160/d/72.jpg">
<img src="https://tse1-mm.cn.bing.net/th?id=OGC.1ac64a61ff1e93c2c3f0754507f6c8aa&pid=1.7&rurl=http%3a%2f%2fimg.lanrentuku.com%2fimg%2fallimg%2f1609%2f5-160914192R6.gif&ehk=8UCm1CrQWYyZ1qMxfhVsHw" class="image" data-src="http://img15.3lian.com/2015/f2/160/d/74.jpg">
<h1>xcc</h1>
<img src="https://tse1-mm.cn.bing.net/th?id=OGC.1ac64a61ff1e93c2c3f0754507f6c8aa&pid=1.7&rurl=http%3a%2f%2fimg.lanrentuku.com%2fimg%2fallimg%2f1609%2f5-160914192R6.gif&ehk=8UCm1CrQWYyZ1qMxfhVsHw" class="image" data-src="http://img15.3lian.com/2015/f2/160/d/75.jpg">
当h1出现在视窗时,$('.wrap').height() + $('.wrap').scrollTop() >= $('h1').offset().top
为true,
也就是当
$('.wrap').height() + $('.wrap').scrollTop() >= $('h1').offset().top
为true时,这个图片就加载jq实现:
start()//初始化加载图片
//触发滚动事件
$('.wrap').on('scroll',function() {
start()
})
function start(){
$('.image').each(function(){
var $node = $(this)
if(show($node)){
changeSrc($node)
}
})
}
//显示出来
function show($node){
return $('.wrap').height() + $('.wrap').scrollTop() >= $('h1').offset().top
}
//替换src
function changeSrc($node){
$node.attr('src',$node.attr('data-src'))
}
网友评论