2020-06-16

简单实现前端图片懒加载

示例代码如下:

<!DOCTYPE html>
<html>
  <head>
    <meta name="generator" content="HTML Tidy for HTML5 for Windows version 5.6.0">
    <meta charset="UTF-8">
    <title>
      实现简单的懒加载Demo
    </title>
    <style>
    img {
    display: block;
    margin-bottom: 50px;
    width: 400px;
    height: 400px;
    }
    </style>
	<script type="text/javascript" src="./jquery-2.2.0.min.js"></script>
  </head>
  <body>
    <img src="" data-src="WordPress/wp-content/themes/twentyseventeen/assets/images/coffee.jpg" alt="">
	<img src="" data-src="WordPress/wp-content/themes/twentyseventeen/assets/images/espresso.jpg" alt="">
	<img src="" data-src="WordPress/wp-content/themes/twentyseventeen/assets/images/header.jpg" alt="">
	<img src="" data-src="WordPress/wp-content/themes/twentyseventeen/assets/images/sandwich.jpg" alt="">
	<img src="" data-src="WordPress/wp-content/themes/twentyseventeen/assets/images/coffee.jpg" alt="">
	<img src="" data-src="WordPress/wp-content/themes/twentyseventeen/assets/images/espresso.jpg" alt="">
	<img src="" data-src="WordPress/wp-content/themes/twentyseventeen/assets/images/header.jpg" alt="">
	<img src="" data-src="WordPress/wp-content/themes/twentyseventeen/assets/images/sandwich.jpg" alt="">
	<img src="" data-src="WordPress/wp-content/themes/twentyseventeen/assets/images/coffee.jpg" alt="">
	<img src="" data-src="WordPress/wp-content/themes/twentyseventeen/assets/images/espresso.jpg" alt="">
	<img src="" data-src="WordPress/wp-content/themes/twentyseventeen/assets/images/header.jpg" alt="">
	<img src="" data-src="WordPress/wp-content/themes/twentyseventeen/assets/images/sandwich.jpg" alt=""> 
    <script type="text/javascript">
    /*js版*/
    /*var num = document.getElementsByTagName('img').length;
    var img = document.getElementsByTagName("img");
    var n = 0; //存储图片加载到的位置,避免每次都从第一张图片开始遍历
    lazyload(); //页面载入完毕加载可是区域内的图片
    window.onscroll = lazyload;
    function lazyload() { //监听页面滚动事件
		var seeHeight = document.documentElement.clientHeight; //可见区域高度
		var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; //滚动条距离顶部高度
		for (var i = n; i < num; i++) {
			if (img[i].offsetTop < seeHeight + scrollTop) {
				if (img[i].getAttribute("src") == "") {
					img[i].src = img[i].getAttribute("data-src");
				}
				n = i + 1;
			}
		}
    }
	*/
	/*JQ版本*/
	var n = 0,
    imgNum = $("img").length;
    img = $('img');
    lazyload();
    $(window).scroll(lazyload);
    function lazyload(event) {
        for (var i = n; i < imgNum; i++) {
            if (img.eq(i).offset().top < parseInt($(window).height()) + parseInt($(window).scrollTop())) {
                if (img.eq(i).attr("src") == "") {
                    var src = img.eq(i).attr("data-src");
                    img.eq(i).attr("src", src);
                    n = i + 1;
                }
            }
        }
    }
</script>
  </body>
</html>

方法二:

// 先进行一次检查
    lazyRender();
    
    function lazyRender () {
        jQuery('#detail img').each(function () {
            if (checkShow(jQuery(this)) && !isLoaded(jQuery(this)) ){
                loadImg(jQuery(this));
            }
        })
    }

    var clock; //这里的clock为timeID,
    jQuery(window).on('scroll',function () {//当页面滚动的时候绑定事件
        if (clock) { // 如果在300毫秒内进行scroll的话,都会被clearTimeout掉,setTimeout不会执行。
                     // 如果有300毫秒外的操作,会得到一个新的timeID即clock,会执行一次setTimeout,然后保存这次setTimeout的ID,
                     // 对于300毫秒内的scroll事件,不会生成新的timeID值,所以会一直被clearTimeout掉,不会执行setTimeout.
            clearTimeout(clock);
        }
        //为了不在滚轮滚动过程中就一直判定,设置个 setTimeout,等停止滚动后再去判定是否出现在视野中。
        clock = setTimeout(function () {
            console.log('运行了一次');
            lazyRender();
        },300)
    })

    function checkShow(img) { // 传入一个img的jq对象
        var scrollTop = jQuery(window).scrollTop();  //即页面向上滚动的距离
        var windowHeight = jQuery(window).height(); // 浏览器自身的高度
        //var windowHeight=window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
        var offsetTop = img.offset().top;  //目标标签img相对于document顶部的位置
        console.log(scrollTop, windowHeight, offsetTop);
        if (offsetTop < (scrollTop + windowHeight) && offsetTop > scrollTop) { //在2个临界状态之间的就为出现在视野中的
            return true;
        }
        return false;
    }

    function isLoaded (img) {
        return img.attr('data-src') === img.attr('src'); //如果data-src和src相等那么就是已经加载过了
    }

    function loadImg (img) {
        console.log(img)
        img.attr('src', img.attr('data-src')); // 加载就是把自定义属性中存放的真实的src地址赋给src属性
    }

发表回复

Your email address will not be published. Required fields are marked *