Home >Backend Development >PHP Problem >How to implement delayed loading of images in php

How to implement delayed loading of images in php

王林
王林Original
2020-10-19 11:30:502060browse

php method to implement delayed loading of images: when reaching the specified loading image location, replace the src attribute value of img with the data-src attribute value, such as [imgs[i].src = imgs[i ].getAttribute('data-src');】.

How to implement delayed loading of images in php

#When you reach the specified loading image location, just replace the attribute value of img's src with the attribute value of data-src. At this time, img will request resource.

(Recommended tutorial: php video tutorial)

imgs[i].src = imgs[i].getAttribute('data-src');

Code implementation:




    
    
    
    图片懒加载
    


    
    
    
    
    
    
    
    
    
    
    
    

<script>
        var imgs = document.querySelectorAll(&#39;img&#39;);

        //offsetTop是元素与offsetParent的距离,循环获取直到页面顶部
        function getTop(e) {
            var T = e.offsetTop;
            while(e = e.offsetParent) {
                T += e.offsetTop;
            }
            return T;
        }

        function lazyLoad(imgs) {
            var H = document.documentElement.clientHeight;//获取可视区域高度
            var S = document.documentElement.scrollTop || document.body.scrollTop;
            for (var i = 0; i < imgs.length; i++) {
                if (H + S > getTop(imgs[i])) {
                    imgs[i].src = imgs[i].getAttribute(&amp;#39;data-src&amp;#39;);
                }
            }
        }

        window.onload = window.onscroll = function () { //onscroll()在滚动条滚动的时候触发
            lazyLoad(imgs);
        }
</script>

Related recommendations: php training

The above is the detailed content of How to implement delayed loading of images in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn