[JavaScript]_[初级]_[如何实现图片的滚动懒加载]

Posted infoworld

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[JavaScript]_[初级]_[如何实现图片的滚动懒加载]相关的知识,希望对你有一定的参考价值。

场景

  1. 开发网站时,页面需要支持图片在页面滚动条移动时才加载,类似微信的公众号页面,这样能让页面按需加载。怎么实现?

  2. 在历史页面里,已经有内容使用<img src="https://...">元素标签,并使用富文本编辑器添加图片,而添加的图片就是在src属性里添加超链接的,那么如何不改动原来内容数据的情况下支持图片的滚动加载?

说明

  1. 开发网站目前要求是基于SSR(服务端渲染)的技术方案,方便搜索引擎索引和搜录. 这种SSR的技术其实主要的还是在输入url后,服务端基本上输出大部分的主要内容。 因此页面里直接有<img>输出是正常的。而有些工具,比如谷歌浏览器的lighthouse是有对页面加载速度有一个指标衡量的,大量的图片同步加载会导致加载速度变慢。

  2. 图片滚动加载,实际上涉及到两个部分,一个就是监听<img>所在区域即将或已经在可见区域,另一个就是使用实际的url地址填充到<img>src属性里。

  3. SSR的网站里,可使用JQuery的插件jquery.lazyload.js[1]来实现这个图片滚动加载效果。但是这个js不能修改原有的src内容进行滚动加载,只有原本的值放到属性data-original才可以. 如果使用了富文本编辑添加的图片,那么<img>元素只会添加src属性,如果需要使用jquery.lazyload.js,还得把src属性名改为data-original,即:

    <img data-original="https://img-blog.csdnimg.cn/1eb625d41cb64930af64a788ed278a54.png">
    

    之后在html模板里引入js. threshold是滚动条时,在距离图片显示前的200像素时就开始加载;placeholder是加载原图时的占位图.

    <script type="text/javascript" src="/public/assets/js/jquery.lazyload.min.js"></script>
    
    <script>
        $(document).ready(function () 
            imgArray.lazyload(
    			threshold:200,
    			placeholder:"/public/assets/images/placeholder.png"
    		);
        );
    </script>
    
  4. 另一种如果不想改src属性,那么需要添加一个loading="lazy"属性,这个是在谷歌和火狐浏览器[7]里支持。也是得修改原内容。可以写一个工具来统一更新<img loading="lazy">。 这里实现一个Java方案的替换,判断<img>如果没有loading属性就添加一个. 之后把所有页面内容都过滤一遍。

    /**
         *
         * @param output
         * @param input
         * @param regexPattern  <img((?!loading=)[^>])+>
         * @param strTagPrefix  <img
         * @param strTagReplace <img loading="lazy"
         * @return 是否有替换,没有替换output不会有输出.
         */
        public static boolean AddAttributeKeyValueToHtmlTag(StringBuffer output, String input,
                            String regexPattern,String strTagPrefix, String strTagReplace)
    
            Pattern p = Pattern.compile(regexPattern);
            Matcher m = p.matcher(input);
    
            while (m.find()) 
                String one = m.group();
                m.appendReplacement(output,one.replace(strTagPrefix,strTagReplace));
            
    
            if(output.length() == 0)
                return false;
    
            m.appendTail(output);
            return true;
        
    

    调用方式

    StringBuffer sb = new StringBuffer();
    boolean result = AddAttributeKeyValueToHtmlTag(sb, value, "<img((?!loading=)[^>])+>",
            "<img", "<img loading=\\"lazy\\"");
    
  5. 注意如果原来的网页内容也不想修改,那么以下的方案可以缓解,但是并不能根本上解决。就是在$(document).ready()里读取DOM模型,把<img>src属性值复制给data-original属性,并删除src属性,之后再load事件里把src属性值还原。这种方式在图片多的时候有用,谷歌浏览器会取消不可见区域的图片加载,可以看谷歌浏览器里的Network部分的图片状态。但是需要说明的是浏览器的DOMContentLoaded(ready)状态下,<img>里的src已经发起请求,删除src属性并不能阻止请求发生.

参考

A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute

Page: DOMContentLoaded, load, beforeunload, unload

The lifecycle of an HTML page has three important events:
    DOMContentLoaded – the browser fully loaded HTML, and the DOM tree is built, but external resources like pictures <img> and stylesheets may not yet have loaded.
    load – not only HTML is loaded, but also all the external resources: images, styles etc.
    beforeunload/unload – the user is leaving the page.

Each event may be useful:
    DOMContentLoaded event – DOM is ready, so the handler can lookup DOM nodes, initialize the interface.
    load event – external resources are loaded, so styles are applied, image sizes are known etc.
    beforeunload event – the user is leaving: we can check if the user saved the changes and ask them whether they really want to leave.
    unload – the user almost left, but we still can initiate some operations, such as sending out statistics.
  1. 1.9.3 version Lazy Load | jQuery Plugin Registry

  2. Lazy Load Remastered

  3. jquery.lazyload(懒加载)的使用与配置 - 安蝶

  4. 滚动加载图片(懒加载)实现原理 - flyromance

  5. $( document ).ready() | jQuery Learning Center

  6. Page: DOMContentLoaded, load, beforeunload, unload

  7. lazy-loading-images

以上是关于[JavaScript]_[初级]_[如何实现图片的滚动懒加载]的主要内容,如果未能解决你的问题,请参考以下文章

[JavaScript]_[初级]_[使用HTMLElement.dataset快速读写自定义属性]

[JavaWeb]_[JavaScript]_[如何实现图片的滚动懒加载]

[Javascript]_[初级]_[获取日期的时间间隔-格式化日期时间]

[Javascript]_[初级]_[获取日期的时间间隔-格式化日期时间]

[Javascript]_[初级]_[获取日期的时间间隔-格式化日期时间]

[JavaScript]_[初级]_[不使用JQuery原生Ajax提交表单]