图片懒加载

本文介绍了一种基于JavaScript的图片懒加载技术实现方案。通过监听滚动事件动态加载图片,有效减少页面初始加载时间,提高用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>LazyLoad</title>
    <style type="text/css">
        img {
            display: block;
            width: 500px;
            height: 400px;
        }
    </style>
</head>
<body>
    <img src="" guoyu-src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1497274158197&di=8845befd9fbda1e99e565b9c2298be50&imgtype=0&src=http%3A%2F%2Fuploads.xuexila.com%2Fallimg%2F1503%2F626-15031G42255b3.jpg">
    <img src="" guoyu-src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1497274158196&di=4a38d248001c145c5b4dd31474dedf41&imgtype=0&src=http%3A%2F%2Fpic29.nipic.com%2F20130512%2F11178195_152908769116_2.jpg">
    <img src="" guoyu-src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1497274158196&di=b39e8b14d214b7aa518d7a8328939efb&imgtype=0&src=http%3A%2F%2Fimage16-c.poco.cn%2Fmypoco%2Fmyphoto%2F20141114%2F12%2F4567377520141114124637053.jpg%3F1024x684_120">
    <img src="" guoyu-src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1497274158196&di=f2e7a6ffbfa3f92025c91e6180b5e317&imgtype=0&src=http%3A%2F%2Ffile31.mafengwo.net%2FM00%2F3F%2F26%2FwKgBs1gXBQuAPWGGABOK4vbGpt412.groupinfo.w600.jpeg">
    <img src="" guoyu-src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1497274158195&di=6a073a070b9cea1214efc0994ed6dde1&imgtype=0&src=http%3A%2F%2Fimages3.ctrip.com%2Fwri%2Fimages%2F200610%2F100602312604121954734.jpg">
    <img src="" guoyu-src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1497274158195&di=a9436d83f55b301d1df9cd24f6e367e7&imgtype=0&src=http%3A%2F%2Fcyjctrip.qiniudn.com%2F69015%2F1379755311203p184vt4juft5p1t8q1andgp5ijn11.jpg">
    <img src="" guoyu-src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1497274158195&di=2b6bc6b871d4f7f267169dfcfb727f84&imgtype=0&src=http%3A%2F%2Fcyjctrip.qiniudn.com%2F106357%2F1395933091608p18k21ek6kvj1gv2ta910kn1002m.jpg">


    <script type="text/javascript">
        var aImg = document.querySelectorAll('img');
        var len = aImg.length;
        var n = 0;//存储图片加载到的位置,避免每次都从第一张图片开始遍历
        window.onscroll = function() {
            var seeHeight = document.documentElement.clientHeight;
            var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
            for (var i = n; i < len; i++) {
                if (aImg[i].offsetTop < seeHeight + scrollTop) {
                    if (aImg[i].getAttribute('src') == '') {
                        aImg[i].src = aImg[i].getAttribute('guoyu-src');
                    }
                    n = i + 1;
                    console.log('n = ' + n);
                }
            }
        };
    </script>
</body>
</html>



CSS代码

只是设置图片的一些样式:

<style>
    *{margin: 0;padding: 0;}
    img{width: 50%;display: inline-block;border: 1px solid #ccc;float: left;}
</style>

HTML代码

1.png是一个1*1px的透明图或者带有logo,这样加载快,测试效果的话无所谓,只要能区分开路径不一样就行,jpg 格式图是实际应该加载的图片路径,两个图显示的宽高要一致。data-url存放图片实际路径:


<div id="div">
    <div id="one">
        <img class="img" data-url="img/1.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/2.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/3.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/4.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/5.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/1.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/1.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/1.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/1.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/1.jpg" src="img/2.png" alt="">
    </div>
    <div id="two">
        <img class="img" data-url="img/6.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/7.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/8.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/2.jpg" src="img/2.png" alt="">
    </div>
</div>

JS代码

原理:滚动至#two内容显示出来时,让#two内的图片路径改为实际路径:

<script>
    //首次进入触发判断
    getList();
    function getList(){
        //第一次显示的图片列表高度
        var contentHeight = document.getElementById('one').offsetHeight;
        //设备可用高度
        var availHeight =  window.screen.availHeight;
        //如果不滚动two直接被显示出来
        if (contentHeight<availHeight){
            //遍历#one下的img,然后替换路径
            for(var x = 0;x < document.querySelectorAll('#one .img').length;x++){
                var imgUrl = document.querySelectorAll('#one .img')[x].getAttribute('data-url');
                var img = new Image();
                img.src = imgUrl;
                //img.onload方法里如果不是自调用函数,x会为循环之后的最大值,而不是012...
                img.onload = (function(e){
                    document.querySelectorAll('#one .img')[x].src = document.querySelectorAll('#one .img')[x].getAttribute('data-url');
                })();
            }
            //遍历#two,然后替换路径
            for(var x = 0;x < document.querySelectorAll('#two .img').length;x++){
                var imgUrl = document.querySelectorAll('#two .img')[x].getAttribute('data-url');
                var img = new Image();
                img.src = imgUrl;
                img.onload = (function(e){
                    document.querySelectorAll('#two .img')[x].src = document.querySelectorAll('#two .img')[x].getAttribute('data-url');
                })();
            }
        }else {
            //遍历#one下的img,然后替换路径
            for(var x = 0;x < document.querySelectorAll('#one .img').length;x++){
                var imgUrl = document.querySelectorAll('#one .img')[x].getAttribute('data-url');
                var img = new Image();
                img.src = imgUrl;
                img.onload = (function(e){
                    document.querySelectorAll('#one .img')[x].src = document.querySelectorAll('#one .img')[x].getAttribute('data-url');
                })();
            }
        }
    }
    //#two显示的次数    0是第一次显示
    var twoShowTime = 0;
    //滚动事件
    window.onscroll = function(){
        if (twoShowTime == 0){
            scroll();
        }
    };
    //滚动判断图片是否加载
    function scroll() {
        //#content的高度
        var contentHeight = document.getElementById('one').offsetHeight;
        //设备可用高度
        var availHeight = window.screen.availHeight;
        //滚动的高度
        var scrollHeight = document.body.scrollTop;
        //判断如果显示出来了#two
        if (scrollHeight > contentHeight - availHeight) {
            //遍历#two下的img,然后替换路径
            for (var x = 0; x < document.querySelectorAll('#two .img').length; x++) {
                var imgUrl = document.querySelectorAll('#two .img')[x].getAttribute('data-url');
                var img = new Image();
                img.src = imgUrl;
                //img.onload方法里如果不是自调用函数,x会为循环之后的最大值,而不是012...
                img.onload = (function () {
                    document.querySelectorAll('#two .img')[x].src = document.querySelectorAll('#two .img')[x].getAttribute('data-url');
                })();
            }
            twoShowTime = 1;
        }
    }
</script>

完整代码


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport" />
    <title>图片懒加载</title>
</head>
<style>
    *{margin: 0;padding: 0;}
    img{width: 48%;height: 150px;display: inline;border: 1px solid #ccc;}
</style>
<body>
<div id="div">
    <div id="one">
        <img class="img" data-url="img/1.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/2.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/3.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/4.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/5.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/1.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/1.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/1.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/1.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/1.jpg" src="img/2.png" alt="">
    </div>
    <div id="two">
        <img class="img" data-url="img/6.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/7.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/8.jpg" src="img/2.png" alt="">
        <img class="img" data-url="img/2.jpg" src="img/2.png" alt="">
    </div>
</div>
<script>
    //首次进入触发判断
    getList();
    function getList(){
        //第一次显示的图片列表高度
        var contentHeight = document.getElementById('one').offsetHeight;
        //设备可用高度
        var availHeight =  window.screen.availHeight;
        //如果不滚动two直接被显示出来
        if (contentHeight<availHeight){
            //遍历#one下的img,然后替换路径
            for(var x = 0;x < document.querySelectorAll('#one .img').length;x++){
                var imgUrl = document.querySelectorAll('#one .img')[x].getAttribute('data-url');
                var img = new Image();
                img.src = imgUrl;
                img.onload = (function(e){
                    document.querySelectorAll('#one .img')[x].src = document.querySelectorAll('#one .img')[x].getAttribute('data-url');
                })();
            }
            //遍历#two,然后替换路径
            for(var x = 0;x < document.querySelectorAll('#two .img').length;x++){
                var imgUrl = document.querySelectorAll('#two .img')[x].getAttribute('data-url');
                var img = new Image();
                img.src = imgUrl;
                img.onload = (function(e){
                    document.querySelectorAll('#two .img')[x].src = document.querySelectorAll('#two .img')[x].getAttribute('data-url');
                })();
            }
        }else {
            //遍历#one下的img,然后替换路径
            for(var x = 0;x < document.querySelectorAll('#one .img').length;x++){
                var imgUrl = document.querySelectorAll('#one .img')[x].getAttribute('data-url');
                var img = new Image();
                img.src = imgUrl;
                img.onload = (function(e){
                    document.querySelectorAll('#one .img')[x].src = document.querySelectorAll('#one .img')[x].getAttribute('data-url');
                })();
            }
        }
    }
    //#two显示的次数    0是第一次显示
    var twoShowTime = 0;
    //滚动事件
    window.onscroll = function(){
        if (twoShowTime == 0){
            scroll();
        }
    };
    //滚动判断图片是否加载
    function scroll() {
        //#content的高度
        var contentHeight = document.getElementById('one').offsetHeight;
        //设备可用高度
        var availHeight = window.screen.availHeight;
        //滚动的高度
        var scrollHeight = document.body.scrollTop;
        //判断如果显示出来了#two
        if (scrollHeight > contentHeight - availHeight) {
            //遍历#two下的img,然后替换路径
            for (var x = 0; x < document.querySelectorAll('#two .img').length; x++) {
                var imgUrl = document.querySelectorAll('#two .img')[x].getAttribute('data-url');
                var img = new Image();
                img.src = imgUrl;
                img.onload = (function () {
                    document.querySelectorAll('#two .img')[x].src = document.querySelectorAll('#two .img')[x].getAttribute('data-url');
                })();
            }
            twoShowTime = 1;
        }
    }
</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

随便起的名字也被占用

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值