手动实现图片懒加载

1,017 阅读2分钟

处理方案:

  1. 把所有需要延迟加载的图片用一个盒子包起来,设置宽高和默认占位图
  2. 开始把所有img的scr为空,把真实图片的地址放到img的自定义属性上,让img隐藏
  3. 等到所有其它资源都加载完成后,我们再开始加载图片
  4. 对于很多图片,需要当页面滚动的时候,当前图片区域完全显示出来之后再加载真实图片
  5. 浏览器低端距离页面顶端的偏移
    • 浏览器可视区的高度 + 滚动条卷去的高度
  6. 图片底部距离页面顶端的偏移
    • 图片的高度 + 图片顶端距离body的距离
<style>
    * {
        margin: 0px;
        padding: 0px;
    }
    .imgBox {
        margin: 0px auto 20px;
        width: 800px;
        height: 160px;
        overflow: hidden;
        background: #ccc;
    }
    .imgBox img {
        width: 100%;
        display: none;
        /* margin-top: 300px; */
    }
</style>
<body>
    <div class="container">
        <!-- 单张图片懒加载不用注释下面的代码 -->
        <!-- <div class="imgBox">
            <img src="" data-img="http://www.zhufengpeixun.cn/main/img/banner10.png" />
        </div> -->
    </div>
   
    <script src="./node_modules/jquery/dist/jquery.min.js"></script>
    <script src="./index.js"></script>
</body>
</html>
/* 单张图片延迟加载 */
let $imgBox =  $('.imgBox'),
    $img = $imgBox.children('img');
$(window).on('load scroll',function() { // 页面所有资源加载完成或者是页面滚动  JQ中事件绑定支持多事件绑定
    // console.log('ok',);
    if( $img.attr('isLoad') === 'true') return; // 首先判断图片是否已经加载过了,加载过了,就不再加载了 
    let A = $imgBox.height() + $imgBox.offset().top,
        B = $(this.window).height() + $(window).scrollTop();
    if(B >= A) {
        $img.attr('src',$img.attr('data-img'));
        $img.on('load',function() {
            // $img.css('display','block');
            $img.stop().fadeIn();
        })
        $img.attr('isLoad',true); // 自定义属性的值都是字符串类型的, 
    } 
})
/* 多张图片延迟加载 */

let str = ``;
// fill() 是es6语法,往数组中填充数据
new Array(20).fill(null).forEach((item,index) => {
    str += `<div class="imgBox">
            <img src="" data-img="http://www.zhufengpeixun.cn/main/img/banner10.png" />
        </div>`
})
let $container = $('.container');
$container.html(str);

let $imgBoxs = $container.children('.imgBox');

// 给图片添加延迟加载的事件
$(window).on('load scroll',function() {
    let $B = $(window).height() + $(window).scrollTop();
    $imgBoxs.each((index,item) => {
        let $item = $(item);
        // 图片的高度 + 图片顶部距离body的高度
        let $itemH = $item.height() + $item.offset().top,
            $isLoad = $item.attr('isLoad');
    
        if($B >= $itemH && $isLoad !== 'true') {
            this.console.log('xxx',index);
            $item.attr('isLoad',true); // 自定义属性的值都是字符串类型的,
            let $img = $item.children('img');
            $img.attr('src',$img.attr('data-img'));
            $img.on('load',function() {
                $img.stop().fadeIn();
            })
        }
    })
})