懒加载实现的方法有哪些?(三种方法介绍)

夏枫君_5184

夏枫君_5184

2019-01-08

4304人浏览

转载

本篇文章给大家带来的内容是关于懒加载实现的方法有哪些?(三种方法介绍),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

优势

  1. 性能收益:浏览器加载图片、decode、渲染都需要耗费资源,懒加载能节约性能消耗,缩短onload事件时间。

  2. 节约带宽:这个不需要解释。

通常,我们在html中展示图片,会有两种方式:

  1. img 标签

  2. css background-image

img的懒加载实现

img有两种方式实现懒加载:

  1. 事件监听(scroll、resize、orientationChange)

html>


    <meta>
    <meta>
    <meta>
    <title>event</title>
    <style>
        img {
            background: #F1F1FA;
            width: 400px;
            height: 300px;
            display: block;
            margin: 10px auto;
            border: 0;
        }
    </style>
    @@##@@
    @@##@@
    @@##@@
    @@##@@
    @@##@@ -->
    @@##@@
    @@##@@
    @@##@@
    @@##@@
    @@##@@
    @@##@@
    @@##@@
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            var lazyloadImages = document.querySelectorAll("img.lazy");    
            var lazyloadThrottleTimeout;
            
            function lazyload () {
                if(lazyloadThrottleTimeout) {
                    clearTimeout(lazyloadThrottleTimeout);
                }    
                
                lazyloadThrottleTimeout = setTimeout(function() {
                    var scrollTop = window.pageYOffset;
                    lazyloadImages.forEach(function(img) {
                        if(img.offsetTop < (window.innerHeight + scrollTop)) {
                            img.src = img.dataset.src;
                            img.classList.remove('lazy');
                        }
                    });
                    if(lazyloadImages.length == 0) {
                        document.removeEventListener("scroll", lazyload);
                        window.removeEventListener("resize", lazyload);
                        window.removeEventListener("orientationChange", lazyload);
                    }
                }, 20);
            }
            
            document.addEventListener("scroll", lazyload);
            window.addEventListener("resize", lazyload);
            window.addEventListener("orientationChange", lazyload);
        });
    </script>
  1. Intersection Observer(兼容性问题)

html>


    <meta>
    <meta>
    <meta>
    <title>observer</title>
    <style>
        img {
            background: #F1F1FA;
            width: 400px;
            height: 300px;
            display: block;
            margin: 10px auto;
            border: 0;
        }
    </style>
    @@##@@
    @@##@@ -->
    @@##@@
    @@##@@
    @@##@@
    @@##@@
    @@##@@
    @@##@@
    @@##@@
    @@##@@
    @@##@@
    @@##@@
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            var lazyloadImages = document.querySelectorAll(".lazy");
            var imageObserver = new IntersectionObserver(function(entries, observer) {
                entries.forEach(function(entry) {
                    if (entry.isIntersecting) {
                        var image = entry.target;
                        image.src = image.dataset.src;
                        image.classList.remove("lazy");
                        imageObserver.unobserve(image);
                    }
                });
            });
            lazyloadImages.forEach(function(image) {
                imageObserver.observe(image);
            });
        });
    </script>

background-image的实现

background-image的实现跟img的原理基本是一样的,区别是在对class的处理上:

html>


    <meta>
    <meta>
    <meta>
    <title>background</title>
    <style>
        body {
            margin: 0;
        }
        .bg {
            height: 200px;
        }
        #bg-image.lazy {
            background-image: none;
            background-color: #F1F1FA;
        }
        #bg-image {
            background-image: url("https://ik.imagekit.io/demo/img/image1.jpeg?tr=w-400,h-300");
            background-size: 100%;
        }
    </style>
    <p></p><div class="aritcle_card flexRow artxards">
											<div class="artcardd flexRow">
												<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill13305" title="AgentGen — HTML to PDF & Image"><img
														src="https://img.php.cn/upload/skill/001/246/273/6adaf20cf0281539.jpg" alt="AgentGen — HTML to PDF & Image" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
												<div class="aritcle_card_info flexColumn">
													<a rel="nofollow" href="/xiazai/skill13305" title="AgentGen — HTML to PDF & Image" class="overflowclass">AgentGen — HTML to PDF & Image</a>
													<p class="overflowclass">将 HTML 转换为 PDF 和图片。无需注册,免费版开箱即用(每分钟 1 次请求,含水印)。如需更高频次及去水印……</p>
												</div>
												<a rel="nofollow" href="/xiazai/skill13305" title="AgentGen — HTML to PDF & Image" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
												</a>
											</div>
										</div>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            var lazyloadImages = document.querySelectorAll(".lazy");
            var imageObserver = new IntersectionObserver(function(entries, observer) {
                entries.forEach(function(entry) {
                    if (entry.isIntersecting) {
                        var image = entry.target;
                        image.classList.remove("lazy");
                        imageObserver.unobserve(image);
                    }
                });
            });
            lazyloadImages.forEach(function(image) {
                imageObserver.observe(image);
            });
        });
    </script>

渐进式懒加载

渐进式懒加载,指的是存在降级处理,通常html形式如下:

<a>
  @@##@@
</a>

这样的代码会有2个好处:

  1. 如果js执行失败,可以点击预览

  2. 大小与实际图一致的占位data URI,避免reflow

最终的代码如下:

html>


    <meta>
    <meta>
    <meta>
    <title>progressive</title>
    <style>
        a.progressive {
            position: relative;
            display: block;
            overflow: hidden;
            outline: none;
        }
        a.progressive:not(.replace) {
            cursor: default;
        }
        a.progressive img {
            display: block;
            width: 100%;
            max-width: none;
            height: auto;
            border: 0 none;
        }
        a.progressive img.preview {
            filter: blur(2vw);
            transform: scale(1.05);
        }
        a.progressive img.reveal {
            position: absolute;
            left: 0;
            top: 0;
            will-change: transform, opacity;
            animation: reveal 1s ease-out;
        }
        @keyframes reveal {
            0% {transform: scale(1.05); opacity: 0;}
            100% {transform: scale(1); opacity: 1;}
        }
    </style>
    <a>
        @@##@@
    </a>
    <a>
        @@##@@
    </a>
    <a>
        @@##@@
    </a>
    <a>
        @@##@@
    </a>
    <a>
        @@##@@
    </a>
    <a>
        @@##@@
    </a>
    <script>
        window.addEventListener('load', function() {
            var pItem = document.getElementsByClassName('progressive replace'), timer;

            window.addEventListener('scroll', scroller, false);
            window.addEventListener('resize', scroller, false);
            inView();

            function scroller(e) {
                timer = timer || setTimeout(function() {
                    timer = null;
                    requestAnimationFrame(inView);
                }, 300);
            }

            function inView() {
                var scrollTop = window.pageYOffset;
                var innerHeight = window.innerHeight;
                var p = 0;
                while (p < pItem.length) {
                    var offsetTop = pItem[p].offsetTop;
                    if (offsetTop < (scrollTop + innerHeight)) {
                        loadFullImage(pItem[p]);
                        pItem[p].classList.remove('replace');
                    }
                    else p++;
                }
            }


            function loadFullImage(item) {
                var img = new Image();
                if (item.dataset) {
                    img.srcset = item.dataset.srcset || '';
                    img.sizes = item.dataset.sizes || '';
                }
                img.src = item.href;
                img.className = 'reveal';
                if (img.complete) addImg();
                else img.onload = addImg;

                function addImg() {
                    item.addEventListener('click', function(e) { e.preventDefault(); }, false);
                    item.appendChild(img).addEventListener('animationend', function(e) {
                        var pImg = item.querySelector('img.preview');
                        if (pImg) {
                            e.target.alt = pImg.alt || '';
                            item.removeChild(pImg);
                            e.target.classList.remove('reveal');
                        }
                    });
                }

            }

        }, false);
    </script>

现成库

推荐下面这个库,使用非常简单:https://www.npmjs.com/package/lozad

相关文章

PHP速学视频免费教程(入门到精通)
PHP速学视频免费教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

javascript html

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
Navicat创建数据库教程
Navicat创建数据库教程

本专题整理Navicat创建数据库相关教程,介绍新建前的准备、基础设置和创建后的检查方法。内容兼顾入门学习及实际使用需求,帮助用户了解不同数据库类型下的操作差异,为后续建表、保存数据和日常管理提供参考。

2026.11.20

0

7

Navicat入门教程大全
Navicat入门教程大全

本专题整理Navicat入门教程,从认识软件界面到开展数据库操作,介绍初次使用需要了解的知识和方法。内容兼顾连接配置、数据管理及日常使用中的疑问,方便用户按学习进度查阅,为后续实践和独立操作打好基础。

2026.11.20

0

17

Navicat数据库连接配置指南
Navicat数据库连接配置指南

从确认数据库信息到建立可用连接,本专题串联Navicat连接数据库的相关知识和操作方法。既有初次配置时需要了解的基础内容,也有连接后的检查思路,方便用户按实际需求查阅教程,逐步熟悉数据库连接的设置流程。

2026.11.20

0

10

PHP8.6数组与数据处理教程
PHP8.6数组与数据处理教程

本专题汇总PHP8.6数组与数据处理教程,涵盖CSV读取和导出、引用遍历删除、array_filter回调模式、配置键名冲突、pathinfo文件名校验、GMP大整数进制转换及UTF-8正则筛选,说明升级兼容变化、输入范围和失败处理方法。

2026.11.20

0

8

PHP8.6升级迁移教程
PHP8.6升级迁移教程

本专题汇总PHP8.6升级迁移与弃用接口改造教程,涵盖反射调用、对象属性赋值、标识符更名、构造函数与__debugInfo调整,以及插件类名检查、常量导出、ArrayIterator排序、SPL和DTO查询参数转换,帮助梳理弃用提示并完成代码兼容改造。

2026.11.20

0

10

PHP8.6安装配置与FPM运维教程
PHP8.6安装配置与FPM运维教程

本专题汇总PHP8.6正式版安装部署与FPM运维教程,涵盖Linux并存安装、独立ini配置、扩展重新编译、Nginx切换与回滚、FPM状态监控和慢日志排查,以及环境变量、请求超时、OPcache刷新和预加载配置。

2026.11.20

0

10

Nginx CVE-2026-123007排查与防护指南
Nginx CVE-2026-123007排查与防护指南

Nginx HTTP/2漏洞该怎么修复?本专题围绕CVE-2026-123007,介绍安全版本升级、模块兼容检查和配置恢复方法,以及日志排查、权限设置等后续加固操作,方便你按实际部署情况查找对应教程。

2026.11.20

20

8

GoFrame框架Web开发与路由中间件
GoFrame框架Web开发与路由中间件

本专题聚焦GoFrame框架的Web开发,拆解路由注册与匹配规则、请求参数获取、参数校验与中间件执行顺序,说明统一响应、JWT鉴权、文件上传与接口文档生成的落地方式,并补充优雅重启与测试实践。

2026.11.17

60

15

GoFrame框架安装与gf命令行工具
GoFrame框架安装与gf命令行工具

本专题围绕GoFrame框架的安装与工具链配置展开,讲清Go版本要求、gf命令行的安装方式、代理镜像与依赖准备,说明项目初始化、热编译、交叉编译打包的做法,并整理安装阶段的常见报错与验证步骤。

2026.11.17

80

15

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Gradle 构建性能优化指南
Gradle 构建性能优化指南

共0课时 | 0人学习

Gradle 官方用户手册
Gradle 官方用户手册

共0课时 | 0人学习

Pandas 官方文档与用户指南
Pandas 官方文档与用户指南

共0课时 | 0人学习